VC删除文件夹下所有文件

来源:互联网 发布:可靠性分析软件nessus 编辑:程序博客网 时间:2024/04/30 08:45
//删除文件夹目录(非空)

[cpp] view plaincopyprint?
  1. bool DeleteDirectory(char* sDirName)   
  2. {   
  3.     CFileFind tempFind;   
  4.     char sTempFileFind[200] ;  
  5.       
  6.     sprintf(sTempFileFind,"%s\*.*",sDirName);   
  7.     BOOL IsFinded = tempFind.FindFile(sTempFileFind);   
  8.     while (IsFinded)   
  9.     {   
  10.         IsFinded = tempFind.FindNextFile();   
  11.           
  12.         if (!tempFind.IsDots())   
  13.         {   
  14.             char sFoundFileName[200];   
  15.             strcpy(sFoundFileName,tempFind.GetFileName().GetBuffer(200));   
  16.               
  17.             if (tempFind.IsDirectory())   
  18.             {   
  19.                 char sTempDir[200];   
  20.                 sprintf(sTempDir,"%s\%s",sDirName,sFoundFileName);   
  21.                 DeleteDirectory(sTempDir);   
  22.             }   
  23.             else   
  24.             {   
  25.                 char sTempFileName[200];   
  26.                 sprintf(sTempFileName,"%s\%s",sDirName,sFoundFileName);   
  27.                 DeleteFile(sTempFileName);   
  28.             }   
  29.         }   
  30.     }   
  31.     tempFind.Close();   
  32.     if(!RemoveDirectory(sDirName))   
  33.     {   
  34.         return FALSE;   
  35.     }   
  36.     return TRUE;   
  37. }   


/////////////////////////////////////////
//下面是应用,CString m_strDir 是一个文件夹路径,如:d:downloadpic

[cpp] view plaincopyprint?
  1. BOOL DelAll()  
  2. {  
  3.     if(PathFileExists(m_strDir))       
  4.         DeleteDirectory((LPSTR)(LPCTSTR)m_strDir);  
  5.     return 1;  
  6. }  

如果不进行递归删除。你可以使用API函数SHFileOperation,它可以一次删除目录及其下面的子目录和文件。

示例代码:

[cpp] view plaincopyprint?
  1. <pre name="code" class="cpp">BOOL DelTree(LPCTSTR lpszPath)  
  2.   
  3. {  
  4.   
  5.    SHFILEOPSTRUCT FileOp;  
  6.   
  7.    FileOp.fFlags = FOF_NOCONFIRMATION;  
  8.   
  9.    FileOp.hNameMappings = NULL;  
  10.   
  11.    FileOp.hwnd = NULL;  
  12.   
  13.    FileOp.lpszProgressTitle = NULL;  
  14.   
  15.    FileOp.pFrom = lpszPath;  
  16.   
  17.    FileOp.pTo = NULL;  
  18.   
  19.    FileOp.wFunc = FO_DELETE;  
  20.   
  21.     returnSHFileOperation(&FileOp) == 0;</pre><br>  
  22. <br>  
  23. <pre></pre>  
  24. <p></p>  
  25. <p>}</p>  
  26. <p> </p>  
  27. <pre></pre>  
  28. <pre></pre>  

转自:http://blog.csdn.net/wangjieest/article/details/7000640
原创粉丝点击