天天看点

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