C 实现删除非空文件夹

[cpp] view plain copy
 
 print?
  1. /* 
  2. 文件名:   rd.c 
  3.  
  4. ---------------------------------------------------- 
  5.     c中提供的对文件夹操作的函数,只能对空文件夹进行 
  6. 删除,这使很多初学者在编码过程中产生许多困扰,我也 
  7. 很不爽这件事情,所以编写这个对非空文件夹进行删除的 
  8. 函数,仅供参考。 
  9.  
  10. 注意:本函数编写以VC6为依据,其中关于文件夹的操作函数 
  11.       与标准c有所区别。如VC6中的findclose可能需要用c 
  12.       中的closedir()来代替。 
  13. ---------------------------------------------------- 
  14. 日期         程序员                       变更记录 
  15.  
  16. 2010.4.28    海总(掌门人号)           创建文件,编写函数 
  17.  
  18.  
  19. ---------------------------------------------------- 
  20. */  
  21.   
  22.   
  23.   
  24.   
  25. #include <stdio.h>  
  26. #include <io.h>  
  27. #include <string.h>  
  28. #include <direct.h>  
  29.   
  30. /* 
  31. 函数入口:文件夹的绝对路径 
  32.           const char*  dirPath 
  33.  
  34. 函数功能:删除该文件夹,包括其中所有的文件和文件夹 
  35.  
  36. 返回值:  0  删除  
  37.          -1  路径不对,或其它情况,没有执行删除操作 
  38. */  
  39. int  removeDir(const char*  dirPath)  
  40. {  
  41.   
  42.     struct _finddata_t fb;   //查找相同属性文件的存储结构体  
  43.     char  path[250];            
  44.     long    handle;  
  45.     int  resultone;  
  46.     int   noFile;            //对系统隐藏文件的处理标记  
  47.       
  48.     noFile = 0;  
  49.     handle = 0;  
  50.   
  51.       
  52.     //制作路径  
  53.     strcpy(path,dirPath);  
  54.     strcat (path,"/*");  
  55.   
  56.     handle = _findfirst(path,&fb);  
  57.     //找到第一个匹配的文件  
  58.     if (handle != 0)  
  59.     {  
  60.         //当可以继续找到匹配的文件,继续执行  
  61.         while (0 == _findnext(handle,&fb))  
  62.         {  
  63.             //windows下,常有个系统文件,名为“..”,对它不做处理  
  64.             noFile = strcmp(fb.name,"..");  
  65.               
  66.             if (0 != noFile)  
  67.             {  
  68.                 //制作完整路径  
  69.                 memset(path,0,sizeof(path));  
  70.                 strcpy(path,dirPath);  
  71.                 strcat(path,"/");  
  72.                 strcat (path,fb.name);  
  73.                 //属性值为16,则说明是文件夹,迭代  
  74.                 if (fb.attrib == 16)  
  75.                 {  
  76.                      removeDir(path);     
  77.                 }  
  78.                 //非文件夹的文件,直接删除。对文件属性值的情况没做详细调查,可能还有其他情况。  
  79.                 else  
  80.                 {  
  81.                     remove(path);  
  82.                 }  
  83.             }     
  84.         }  
  85.         //关闭文件夹,只有关闭了才能删除。找这个函数找了很久,标准c中用的是closedir  
  86.         //经验介绍:一般产生Handle的函数执行后,都要进行关闭的动作。  
  87.         _findclose(handle);  
  88.     }  
  89.         //移除文件夹  
  90.         resultone = rmdir(dirPath);  
  91.         return  resultone;  
  92. }  
原文地址:https://www.cnblogs.com/lidabo/p/5462937.html