/
//--zwh--注:删除当前文件夹及其子文件夹与文件(接口);
BOOL CBackupToolDlg::clearFiles(CString strPath)
{
//=========功能概要:删除给定路径下的所有文件========//
/*
* 功能:传入绝对路径,清空此文件夹内的所有内容(做为接口使用,故建议不在此函数内递归);
*/
//==================================================//
BOOL bSuccess = TRUE;//作为in/out参数传入;
ForeachSubDir(strPath,bSuccess);
return bSuccess;
}
//--zwh;
//---zwh--注:递归法遍历并删除当前目录下的所有文件及文件夹;
void CBackupToolDlg::ForeachSubDir(CString strPath,BOOL bSuccess)
{
if (strPath.Right(1)!="\\")
{
strPath += "\\";
}
strPath += "*.*"; //形如c:\windows\system32\*.*
CFileFind fileFinder;
BOOL bFile = fileFinder.FindFile(strPath);
while(bFile)
{
bFile = fileFinder.FindNextFile();
if (fileFinder.IsDirectory() && !fileFinder.IsDots()) //当为文件夹时;
{
CString temp = strPath;
int i = temp.Find("*.*");
temp.Delete(i,3);
temp = temp + fileFinder.GetFileName(); //拿到文件夹的全路径,诸如:c:\windows\system32\drivers
if(fileFinder.GetLength()==0)//如果为空目录,则删除文件夹;
{
RemoveDirectory(temp.GetBuffer());
}
else
{
ForeachSubDir(temp,TRUE);
}
}
else if(!fileFinder.IsDirectory() && !fileFinder.IsDots()) //当为文件时;
{
CString strFullName = fileFinder.GetFilePath();
//因为CFile::Remove可能会抛出CFile的异常,所以应该用try..catch来处理异常;
try
{
CFile::Remove(strFullName.GetBuffer());
}
catch (CFileException* pEx)
{
#ifdef _DEBUG
afxDump << "File " << strFullName.GetBuffer() << " cannot be removed\n";
#endif
pEx->Delete();
bSuccess = FALSE;//遇到异常,返回FALSE;
return ;
}
}
}//--end--while
fileFinder.Close();
}