GetCurrentDirectory,SetCurrentDirectory使用例子

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 07:14   22   0

清理指定目录树中的文件函数:

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;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP