RemoveDirectory()
仅能删除空目录。如何删除其中有文件的目录?
std::filesystem::remove_all
。在此之前,您可以使用Boost实现的boost::filesystem::remove_all
。无论哪种方式,您都不必担心平台特定的问题。
我不知道任何其他独立于平台的解决方案;否则通常的方法将涉及读取目录并递归下降它(但读取目录的方式也使用std::filesystem
、boost::filesystem
或依赖于系统的代码)。SHFileOperation
实现此目的。使用FO_DELETE
操作,并记得双重空终止您的目录名称。SHFileOperation
不是线程安全的。它只能与绝对路径一起安全使用。double directory_delete(char *pathname)
{
string str(pathname);
if (!str.empty())
{
while (*str.rbegin() == '\\' || *str.rbegin() == '/')
{
str.erase(str.size()-1);
}
}
replace(str.begin(),str.end(),'/','\\');
struct stat sb;
if (stat((char *)str.c_str(),&sb) == 0 &&
S_ISDIR(sb.st_mode))
{
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
TCHAR DirPath[MAX_PATH];
TCHAR FileName[MAX_PATH];
_tcscpy(DirPath,(char *)str.c_str());
_tcscat(DirPath,"\\*");
_tcscpy(FileName,(char *)str.c_str());
_tcscat(FileName,"\\");
hFind = FindFirstFile(DirPath,&FindFileData);
if (hFind == INVALID_HANDLE_VALUE) return 0;
_tcscpy(DirPath,FileName);
bool bSearch = true;
while (bSearch)
{
if (FindNextFile(hFind,&FindFileData))
{
if (!(_tcscmp(FindFileData.cFileName,".") &&
_tcscmp(FindFileData.cFileName,".."))) continue;
_tcscat(FileName,FindFileData.cFileName);
if ((FindFileData.dwFileAttributes &
FILE_ATTRIBUTE_DIRECTORY))
{
if (!directory_delete(FileName))
{
FindClose(hFind);
return 0;
}
RemoveDirectory(FileName);
_tcscpy(FileName,DirPath);
}
else
{
if (FindFileData.dwFileAttributes &
FILE_ATTRIBUTE_READONLY)
_chmod(FileName, _S_IWRITE);
if (!DeleteFile(FileName))
{
FindClose(hFind);
return 0;
}
_tcscpy(FileName,DirPath);
}
}
else
{
if (GetLastError() == ERROR_NO_MORE_FILES)
bSearch = false;
else
{
FindClose(hFind);
return 0;
}
}
}
FindClose(hFind);
return (double)(RemoveDirectory((char *)str.c_str()) == true);
}
else
{
return 0;
}
}
如果您想直接使用我的代码,需要在您的cpp文件顶部添加以下标头:
#include <windows.h> // winapi
#include <sys/stat.h> // stat
#include <tchar.h> // _tcscpy,_tcscat,_tcscmp
#include <string> // string
#include <algorithm> // replace
using namespace std;
...我觉得就是这样。
我的代码基于这篇文章:
http://www.codeguru.com/cpp/w-p/files/folderdirectorymaintenance/article.php/c8999/删除目录包括子文件夹.htm
我强烈建议不要使用SHFileOperation
,除了安全问题外,它已经被IFileOperation
取代自Windows Vista。
system("rd /s /q ...");
虽然它看起来不太好看,但它太简单了,不能忽视。它还解决了所有关于网络共享文件处理的问题。无论你想出什么解决方案,都可能是rd
的(不完整和/或不正确的)重新实现,因此调用外部进程实际上是很好的代码重用。 ;-)
SHFileOperation
可用的可能性更大(SHFileOperation
自Windows XP以来一直存在,并且已经在Windows Vista中被弃用)。 - Frerich Raabesystem()
则在1%到100%之间。我总是努力开发可以运行或无法运行的代码。半个运行的程序真的很难调试。如果rd
真的节省了我的时间,那么我会把一部分节省下来的时间用于运行时验证。 - Sebastian Mach