C++ 删除非空文件夹及文件夹下的文件

 1 int  removeDir(string dirPath)
 2 {
 3     struct _finddata_t fb;   //find the storage structure of the same properties file.
 4     string path;
 5     long    handle;
 6     int  resultone;
 7     int   noFile;            // the tag for the system's hidden files
 8 
 9     noFile = 0;
10     handle = 0;
11 
12     path = dirPath + "/*";
13 
14     handle = _findfirst(path.c_str(), &fb);
15 
16     //find the first matching file
17     if (handle != -1)
18     {
19         //find next matching file
20         while (0 == _findnext(handle, &fb))
21         {
22             // "." and ".." are not processed
23             noFile = strcmp(fb.name, "..");
24 
25             if (0 != noFile)
26             {    
27                 path.clear();
28                 path = dirPath + "/" + fb.name;
29 
30                 //fb.attrib == 16 means folder
31                 if (fb.attrib == 16)
32                 {
33                     removeDir(path);
34                 }                
35                 else
36                 {
37                     //not folder, delete it. if empty folder, using _rmdir istead.
38                     remove(path.c_str());
39                 }
40             }
41         }
42         // close the folder and delete it only if it is closed. For standard c, using closedir instead(findclose -> closedir).
43         // when Handle is created, it should be closed at last.  
44         _findclose(handle);
      return 0;
45 }

 

posted @ 2018-03-16 09:37  hudalikm  阅读(6270)  评论(2编辑  收藏  举报