引用:codeguru.com/forum/showthread.php?t=239271
当使用下面的功能删除文件夹时,除最上面的文件夹外,所有文件夹、子文件夹和文件都会被删除。假设路径 c:\folder1\folder2
folder2
下的所有内容都被删除,除了 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
}
如果您能帮助我们找到问题,我们将不胜感激。
在调试期间,我注意到 FindClose
函数已成功关闭文件句柄,但 GetLastError
返回 32(“该进程无法访问该文件,因为它正被另一个进程使用” ) 但是,在尝试使用流程资源管理器后,我一无所知。
最佳答案
虽然您可以通过这种方式删除目录,但让系统通过调用SHFileOperation
为您删除会更简单。通过 FO_DELETE
。请记住,您必须对传递给此 API 的字符串进行双重空终止。
关于c++ - 为什么 RemoveDirectory 函数不删除最顶层的文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9683764/