天天看點

windows api 實作删除指定目錄下的所有檔案(包括子檔案夾下的所有檔案)

windows  api實作了這個功能,代碼如下:

[cpp]  view plain copy

  1. BOOL IsDirectory(const char *pDir)  
  2. {  
  3.     char szCurPath[500];  
  4.     ZeroMemory(szCurPath, 500);  
  5.     sprintf_s(szCurPath, 500, "%s/  
  6.     if( hFile == INVALID_HANDLE_VALUE )   
  7.     {  
  8.         FindClose(hFile);  
  9.         return FALSE;   
  10.     }else  
  11.     {     
  12.         FindClose(hFile);  
  13.         return TRUE;  
  14.     }  
  15. }  
  16. BOOL DeleteDirectory(const char * DirName)  
  17. {  
  18. //  CFileFind tempFind;     //聲明一個CFileFind類變量,以用來搜尋  
  19.     char szCurPath[MAX_PATH];       //用于定義搜尋格式  
  20.     _snprintf(szCurPath, MAX_PATH, "%s//*.*", DirName); //比對格式為*.*,即該目錄下的所有檔案  
  21.     WIN32_FIND_DATAA FindFileData;        
  22.     ZeroMemory(&FindFileData, sizeof(WIN32_FIND_DATAA));  
  23.     HANDLE hFile = FindFirstFileA(szCurPath, &FindFileData);  
  24.     BOOL IsFinded = TRUE;  
  25.     while(IsFinded)  
  26.     {  
  27.         IsFinded = FindNextFileA(hFile, &FindFileData); //遞歸搜尋其他的檔案  
  28.         if( strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..") ) //如果不是"." ".."目錄  
  29.         {  
  30.             string strFileName = "";  
  31.             strFileName = strFileName + DirName + "//" + FindFileData.cFileName;  
  32.             string strTemp;  
  33.             strTemp = strFileName;  
  34.             if( IsDirectory(strFileName.c_str()) ) //如果是目錄,則遞歸地調用  
  35.             {     
  36.                 printf("目錄為:%s/n", strFileName.c_str());  
  37.                 DeleteDirectory(strTemp.c_str());  
  38.             }  
  39.             else  
  40.             {  
  41.                 DeleteFileA(strTemp.c_str());  
  42.             }  
  43.         }  
  44.     }  
  45.     FindClose(hFile);  
  46.     BOOL bRet = RemoveDirectoryA(DirName);  
  47.     if( bRet == 0 ) //删除目錄  
  48.     {  
  49.         printf("删除%s目錄失敗!/n", DirName);  
  50.         return FALSE;  
  51.     }  
  52.     return TRUE;  
  53. }  

使用時,直接調用即可,如:DeleteDirectory("C:");删除c盤下的所有的檔案以及檔案夾,當然對于windows不允許删除的檔案,也是不可以删除的,相關聯的上層檔案夾等等都不可删除,因為不能夠删除非空的檔案夾。

原文位址:http://blog.csdn.net/jaff20071234/article/details/6559533