删除文件夹下所有文件

时间:2021-06-17 09:56:55

// 删除文件夹下的所有文件 VC6.0下测试通过
BOOL DelDirFiles(CString strPath)
{
WIN32_FIND_DATA wfd;
HANDLE hFind;
CString strFullPath;
CString strFindFilter;
DWORD dwAttributes = 0;

strFindFilter = strPath + _T("\\*.*");
hFind = FindFirstFile(strFindFilter, &wfd);
if (INVALID_HANDLE_VALUE == hFind)
{
return FALSE;
}

do
{
if (_tcscmp(wfd.cFileName, _T(".")) == 0 ||
_tcscmp(wfd.cFileName, _T("..")) == 0 )
{
continue;
}

strFullPath = strPath + _T("\\") + wfd.cFileName;
//去掉只读属性
dwAttributes = GetFileAttributes(strFullPath);
if (dwAttributes & FILE_ATTRIBUTE_READONLY)
{
dwAttributes &= ~FILE_ATTRIBUTE_READONLY;
SetFileAttributes(strFullPath, dwAttributes);
}

if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
DelDirFiles(strFullPath);
RemoveDirectory(strFullPath);
}
else
{
DeleteFile(strFullPath);
}
}while (FindNextFile(hFind, &wfd));

FindClose(hFind);

return TRUE;
}