这个方法好像是参考Stack Overflow上面的,具体的那篇文章我也忘了!若有看到的可提供下链接,谢谢!
不多说,直接上代码
int DeleteDirectory(const string &refcstrRootDirectory, bool bDeleteSubdirectories)
{
bool bSubdirectory = false; // Flag, indicating whether
// subdirectories have been found
HANDLE hFile; // Handle to directory
std::string strFilePath; // Filepath
std::string strPattern; // Pattern
WIN32_FIND_DATA FileInformation; // File information
strPattern = refcstrRootDirectory + "\\*.*";
hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if (hFile != INVALID_HANDLE_VALUE)
{
do
{
if (FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
if (FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (bDeleteSubdirectories)
{
// Delete subdirectory
int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
if (iRC)
return iRC;
}
else
bSubdirectory = true;
}
else
{
// Set file attributes
if (::SetFileAttributes(strFilePath.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();
// Delete file
if (::DeleteFile(strFilePath.c_str()) == FALSE)
return ::GetLastError();
}
}
} while (::FindNextFile(hFile, &FileInformation) == TRUE);
// Close handle
::FindClose(hFile);
DWORD dwError = ::GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
return dwError;
else
{
if (!bSubdirectory)
{
// Set directory attributes
if (::SetFileAttributes(refcstrRootDirectory.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();
// Delete directory
if (::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
return ::GetLastError();
}
}
}
return 0;
}