haha0518 发表于 2017-6-2 13:28:27

递归删除一个目录

CFindFile的使用框架:
void Recurse(LPCTSTR pstr)
{
   CFileFind finder;

   // build a string with wildcards
   CString strWildcard(pstr);
   strWildcard += _T("\\*.*");

   // start working for files
   BOOL bWorking = finder.FindFile(strWildcard);

   while (bWorking)
   {
      bWorking = finder.FindNextFile();

      // skip . and .. files; otherwise, we'd
      // recur infinitely!

      if (finder.IsDots())
         continue;

      // if it's a directory, recursively search it

      if (finder.IsDirectory())
      {
         CString str = finder.GetFilePath();
         TRACE(_T("%s\n"), (LPCTSTR)str);
         Recurse(str);
      }
   }

   finder.Close();
}





递归删除

//循环删除一个目录
void RecursiveDelete(CString strDir)
{
        CFileFind ff;
        CString strPath;
        strPath = strDir;
        if (strPath.Right(1) != '\\')
        {
                strPath += '\\';
        }
        strPath += "*.*";

        BOOL bWorking = ff.FindFile(strPath);
        while (bWorking)
        {
                bWorking = ff.FindNextFile();

                // skip . and .. files; otherwise, we'd
                // recur infinitely!
                if (ff.IsDots())
                        continue;

                // if it's a directory, recursively search it

                if (ff.IsDirectory())
                {
                        //递归目录
                        CString str = ff.GetFilePath();
                        TRACE(_T("%s\n"), (LPCTSTR)str);
                        RecursiveDelete(str);
                        //删除目录
                        ::SetFileAttributesA(str, FILE_ATTRIBUTE_NORMAL);
                        ::RemoveDirectory(str);
                }
                else
                {
                        //删除文件
                        CString str = ff.GetFilePath();
                        TRACE(_T("%s\n"), (LPCTSTR)str);
                        ::SetFileAttributes(str, FILE_ATTRIBUTE_NORMAL);
                        ::DeleteFile(str);
                }
        }

        ff.Close();

       


}
int main(int argc, char *argv[])
{
        RecursiveDelete("C:\\20_128\\");
        return 0;
}
页: [1]
查看完整版本: 递归删除一个目录