Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

c++ - Why is RemoveDirectory function not deleting the top most folder?

refer: codeguru.com/forum/showthread.php?t=239271

When using the function below to delete folders, all folders, subfolders and files are getting deleted except for the top most folder. Say for the path c:folder1folder2 every thing under folder2 is deleted except for folder2.

BOOL DeleteDirectory(const TCHAR* sPath)  
{  
    HANDLE hFind; // file handle
    WIN32_FIND_DATA FindFileData;

    TCHAR DirPath[MAX_PATH];
    TCHAR FileName[MAX_PATH];

    _tcscpy(DirPath,sPath);
    _tcscat(DirPath,_T(""));
    _tcscpy(FileName,sPath);
    _tcscat(FileName,_T("\*")); // searching all files
    int nRet = 0;
    hFind = FindFirstFile(FileName, &FindFileData); // find the first file
    if( hFind != INVALID_HANDLE_VALUE ) 
    {
        do
        {
            if( IsDots(FindFileData.cFileName) ) 
                continue; //if not directory continue

            _tcscpy(FileName + _tcslen(DirPath), FindFileData.cFileName);
            if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
            {
                // we have found a directory, recurse
                if( !DeleteDirectory(FileName) ) 
                    break;   // directory couldn't be deleted
            }
            else 
            {
                if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
                    _wchmod(FileName, _S_IWRITE); // change read-only file mode

                if( !DeleteFile(FileName) ) 
                    break;  // file couldn't be deleted
            }
        }while( FindNextFile(hFind, &FindFileData) );

        nRet = FindClose(hFind); // closing file handle
    }

    return RemoveDirectory(sPath); // remove the empty (maybe not) directory and returns zero when RemoveDirectory function fails
}  

Any help in finding the issue is appreciated. During debugging I noticed that the FindClose function was successfully closing the file handle but GetLastError was returning 32 ("The process cannot access the file because it is being used by another process") However I have no clue after trying with process explorer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Whilst you can delete a directory this way, it's simpler to let the system do it for you by calling SHFileOperation passing FO_DELETE. Remember that you must double null-terminate the string you pass to this API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...