利用递归删除文件夹(文件夹中套文件夹)

//删除目录

bool deldir(const AnsiString &P)

{

    if(P.IsEmpty()||P.Length()<4)

        return false;//参数必须大于3,即不能为磁盘根目录或空白

    int len = P.Length();

    char* Path = P.c_str();

    AnsiString Dir = "";

    AnsiString str = "/";

    if(Path[len-1] != '//')

        Dir = P + str;

    AnsiString Files = Dir + "*.*"; //识别文件

    WideString b(Files);

    WIN32_FIND_DATA wfd;

    HANDLE hFind = FindFirstFile(b.c_bstr(),&wfd);

    bool Ret = true;

    AnsiString Tmp;

    if(hFind != INVALID_HANDLE_VALUE)  //是否有文件

    {

        bool bFind = true;

        while(bFind)

        {

            if(wfd.cFileName[0]!='.')

            {

                Tmp = Dir + wfd.cFileName;

                if(wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)

                {//删除所有子目录

 

                    Ret = Ret && deldir(Tmp); //如果文件夹中有文件夹,调用自身进行递归删除

                }

                else

                {//删除所有文件

                    WideString c(Tmp);

                    SetFileAttributes(c.c_bstr(),FILE_ATTRIBUTE_NORMAL);

                    Ret = Ret && DeleteFile(Tmp);

                }

            }

            bFind = FindNextFile(hFind,&wfd);

        }

        FindClose(hFind);

    }

    if(Ret)

        return RemoveDir(Path);

    return false;

}

你可能感兴趣的:(C++Builder,C++)