您的位置:首页 > 其它

删除不为空目录的两种实现方式

2010-10-14 23:49 344 查看
删除不为空目录的两种实现方式 收藏

http://blog.csdn.net/vcforever/archive/2004/12/06/206352.aspx
众所周知删除不为空的目录的过程其实是一个函数递归调用的过程
其实现过程无非是通过调用MFC中的CFileFind类的FindFile以及
FindNextFile或者Windows API 中的FindFirstFile以及FindNextFile
等函数实现,只是使用CFileFind类的实现过程较API的实现过程比较
简单而已,下面通过两种方式来实现该删除不为空的目录功能

//使用MFC中的CFileFind类实现删除不为空的目录
bool __stdcall deleteDirectory(const char* pszDir)
{
CFileFind tempFind;
char tempFileFind[MAX_PATH];
sprintf(tempFileFind,"%s//*.*",pszDir);

bool IsFinded = reinterpret_cast<bool>(tempFind.FindFile(tempFileFind));

while (IsFinded) {
//此处的reinterpret_cast强制类型转换是为了将BOOL类型转换成bool类型
IsFinded = reinterpret_cast<bool>(tempFind.FindNextFile());
if (!tempFind.IsDots()) {
char foundFileName[MAX_PATH];
strcpy(foundFileName,tempFind.GetFileName().GetBuffer(MAX_PATH));
if (tempFind.IsDirectory()) {////如果是目录的话则递归调用函数本身
char tempDir[MAX_PATH];
sprintf(tempDir,"%s//%s",pszDir,foundFileName);
deleteDirectory(tempDir);
}
else { //如果是文件的话删除该文件
char tempFileName[MAX_PATH];
sprintf(tempFileName,"%s//%s",pszDir,foundFileName);
DeleteFile(tempFileName);
}
}
}
tempFind.Close();

if (!RemoveDirectory(pszDir))//删除目录
return false;

return true;
}

//使用API方式实现删除不为空的目录
bool deleteDirectory(const char* pszDir)
{
WIN32_FIND_DATA fd;
char szTempFileFind[MAX_PATH] = { 0 };
bool bIsFinish = false;

ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));

sprintf(szTempFileFind, "%s//*.*", pszDir);

HANDLE hFind = FindFirstFile(szTempFileFind, &fd);
if (hFind == INVALID_HANDLE_VALUE)
return false;

while (!bIsFinish) {
bIsFinish = (FindNextFile(hFind, &fd)) ? false : true;
if ((strcmp(fd.cFileName, ".") != 0) && (strcmp(fd.cFileName, "..") != 0)) {
char szFoundFileName[MAX_PATH] = { 0 };
strcpy(szFoundFileName, fd.cFileName);

if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
char szTempDir[MAX_PATH] = { 0 };
sprintf(szTempDir, "%s//%s", pszDir, szFoundFileName);
deleteDirectory(szTempDir);
}
else {
char szTempFileName[MAX_PATH] = { 0 };
sprintf(szTempFileName, "%s//%s", pszDir, szFoundFileName);
DeleteFile(szTempFileName);
}
}
}
FindClose(hFind);

if (!RemoveDirectory(pszDir))
return false;
return true;
}

上面就是删除不为空的文件夹的两种实现方式,其基本思路并无差别
只是使用MFC的方式比直接使用API要简便一些,仅此而已!



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/vcforever/archive/2004/12/06/206352.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: