windows 删除文件夹下所有文件
template<typename T>
struct EnsureFileCloseHelper
{
EnsureFileCloseHelper(T& handle, bool findHandle = false) : t(handle), IsFind(findHandle) {}
~EnsureFileCloseHelper() { (!IsFind) ? (::CloseHandle(t)) : (::FindClose(t)); }
T& t;
bool IsFind;
};
bool DeleteDirectory(std::wstring & sDirName)
{
WIN32_FIND_DATA findFileData;
std::wstring filePathFind = sDirName + _T("\\*.*");
std::wstring fileName;
if(sDirName[sDirName.length() - 1] != '\\' && sDirName[sDirName.length() - 1] != '/') { sDirName += L"\\"; }
HANDLE hFind = ::FindFirstFile(filePathFind.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
EnsureFileCloseHelper<HANDLE> handleHelper(hFind, true);
while (::FindNextFile(hFind, &findFileData))
{
const std::wstring & fileName = findFileData.cFileName;
if (L"." == fileName || L".." == fileName)
{
continue;
}
else if (FILE_ATTRIBUTE_DIRECTORY == findFileData.dwFileAttributes)
{
DeleteDirectory(sDirName + findFileData.cFileName);
}
else if (FILE_ATTRIBUTE_DIRECTORY != findFileData.dwFileAttributes)
{
fileName = findFileData.cFileName;
::DeleteFile(std::wstring(sDirName + fileName).c_str());
}
}
}
if(!RemoveDirectory(sDirName.c_str()))
{
return false;
}
return true;
}