清理指定目录树中的文件函数:
BOOL CTmpBatchDlg::RemoveDirectoryTree(CString strDirName)
{
//检测目录是否存在, 不存在则返回
if (_access(strDirName, 0))
{
return TRUE;
}
//获取目录字节数(GetCurrentDirectory中第一个参数给零, 就是可以返回具体所需字节数大小)
UINT uSize = ::GetCurrentDirectory(0, NULL) * sizeof(TCHAR);
//获取当前进程句柄
HANDLE hHeap = ::GetProcessHeap();
//分配当前进程相同大小的内存并清空
LPTSTR lpBuffer = (LPTSTR)::HeapAlloc(hHeap, HEAP_ZERO_MEMORY, uSize);
//获取当前目录的内容并复制到lpBuffer中
::GetCurrentDirectory(uSize, lpBuffer);
if (lpBuffer != strDirName)
{
::SetCurrentDirectory(strDirName);
}
BOOL bResult;
CString strTempFile;
//文件属性结构
WIN32_FIND_DATA FindFileData;
HANDLE hFindFile = ::FindFirstFile("*.*", &FindFileData);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{ //目录名或文件名
strTempFile = FindFileData.cFileName;
if (strTempFile == "." || strTempFile == "..")
{
continue;
}
if (FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
if (strDirName.Right(1) != '\\')
{
RemoveDirectoryTree(strDirName + '\\' + strTempFile);
}
else
{
RemoveDirectoryTree(strDirName + strTempFile);
}
}
else
{
if (!::DeleteFile(strTempFile))
{
bResult = FALSE;
}
else
{
bResult = TRUE;
}
}
} while (::FindNextFile(hFindFile, &FindFileData));
::FindClose(hFindFile);
if (lpBuffer == strDirName)
{
::SetCurrentDirectory("c:\\");
}
else
{//strDirName有可能变化了,但lpBuffer保存了初始的strDirName
::SetCurrentDirectory(lpBuffer);
}
}
else
{
bResult = FALSE;
}
::HeapFree(hHeap, NULL, lpBuffer);
return bResult;
}