Mar*_*tin 3 c c++ windows winapi win32-process
参考: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
}
Run Code Online (Sandbox Code Playgroud)
任何帮助找到问题的人都表示赞赏.在调试期间,我注意到该FindClose函数已成功关闭文件句柄但GetLastError返回32("进程无法访问该文件,因为它正被另一个进程使用")但是我在尝试使用进程资源管理器后没有任何线索.
虽然您可以通过这种方式删除目录,但让系统通过调用SHFileOperation传递为您执行此操作更为简单FO_DELETE.请记住,必须对传递给此API的字符串进行双重null终止.