删除文件夹,需要考虑到文件夹内部还有其他文件或文件夹,这样的话windows sdk提供的RemoveDirectory就不能起作用了,需要自己再写一个函数来实现。
RemoveDirectory msdn里面提到了 SHFileOperation,下面就先以SHFileOperation来实现删除文件夹
在vs2010中编译测试过,没有问题,速度也挺快的
//函数名:DeleteFolder
//输入参数:LpszPath 要删除的路径指针
//作用:删除指定文件夹以及里面的文件
//
/////////////////////////////////////
BOOL DeleteFolder(LPCTSTR lpszPath)
{
int nLength = strlen(lpszPath);
char *NewPath = new char[nLength+2];
strcpy(NewPath,lpszPath);
NewPath[nLength] = '\0';
NewPath[nLength+1] = '\0';
SHFILEOPSTRUCT FileOp;
ZeroMemory((void*)&FileOp,sizeof(SHFILEOPSTRUCT));
FileOp.fFlags = FOF_NOCONFIRMATION;
FileOp.hNameMappings = NULL;
FileOp.hwnd = NULL;
FileOp.lpszProgressTitle = NULL;
FileOp.pFrom = NewPath;
FileOp.pTo = NULL;
FileOp.wFunc = FO_DELETE;
return SHFileOperation(&FileOp) == 0;
}
其他两种方式,没有测试过,不过看逻辑好像没有问题:
void DeleteDirectory(CString strDir)
{
if(strDir.IsEmpty())
return;
// 首先删除文件及子文件夹
CFileFind ff;
BOOL bFound = ff.FindFile(strDir+"\\*", 0);
while(bFound)
{
bFound = ff.FindNextFile();
if(ff.GetFileName()=="."||ff.GetFileName()=="..")
continue;
// 去掉文件(夹)只读等属性
SetFileAttributes(ff.GetFilePath(), FILE_ATTRIBUTE_NORMAL);
if(ff.IsDirectory())
{
// 递归删除子文件夹
DeleteDirectory(ff.GetFilePath());
RemoveDirectory(ff.GetFilePath());
}
else
{
// 删除文件
DeleteFile(ff.GetFilePath());
}
}
ff.Close();
// 然后删除该文件夹
RemoveDirectory(strDir);
}
BOOL DeleteDirectory(LPCTSTR DirName)
{
CFileFind tempFind;
char tempFileFind[200];
sprintf(tempFileFind,"%s\\*.*",DirName);
BOOL IsFinded=(BOOL)tempFind.FindFile(tempFileFind);
while(IsFinded)
{
IsFinded=(BOOL)tempFind.FindNextFile();
if(!tempFind.IsDots()) // 如果不是'.'或者'..'
{
char foundFileName[200];
strcpy(foundFileName,tempFind.GetFileName().GetBuffer(200));
if(tempFind.IsDirectory()) //是否是目录
{
char tempDir[200];
sprintf(tempDir,"%s\\%s",DirName,foundFileName);
DeleteDirectory(tempDir);
}
else //若是文件,则删除
{
char tempFileName[200];
sprintf(tempFileName,"%s\\%s",DirName,foundFileName);
DeleteFile(tempFileName);
}
}
}
tempFind.Close();
if(!RemoveDirectory(DirName))
{
AfxMessageBox("删除目录失败!",MB_OK);
return FALSE;
}
return TRUE;
}
参考文章:
http://www.yuloo.com/news/1007/444817.html
http://xbgd.iteye.com/blog/663025