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. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM