MFC--删除指定目录下的文件夹及其文件

/

//--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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值