简体   繁体   中英

Recursively delete a directory in C

I have to delete recursively a directory which is not necessarily empty in C for my OS class. I tried to do so ,but it doesn't seem to work . I don't have errors in my code when I compile it though. Any suggestions would help me a lot .

 #include <stdio.h> 
 #include <sys/stat.h>
 #include <dirent.h> 


int main(int argc,char* argv[])
{ 


   if (argc<2) {
              printf("Wrong numer of arguments\n");
              return 1;
               }


 int is_dir (char * filename) 
  { 
    struct stat buf; 
    int ret = stat (filename, & buf); 
    if (0 == ret) 
     { 
       if (buf.st_mode & S_IFDIR) 
        { 
          return 0; 
        } 
      else 
       { 
         return 1; 
       } 
    } 
     return -1; 
  }

  int delete_dir (char * dirname) 
   { 
      char chBuf [256]; 
      DIR * dir = NULL; 
      struct dirent * ptr; 
      int ret = 0; 
     dir = opendir (dirname); 
     if (NULL == dir) 
      { 
        return -1; 
} 
   while ((ptr = readdir (dir))!= NULL) 
    { 
      ret = strcmp (ptr-> d_name, "."); 
      if (0 == ret) 
   { 
    continue; 
   } 
   ret = strcmp (ptr-> d_name, ".."); 
   if (0 == ret) 
    { 
      continue; 
    } 
     snprintf (chBuf, 256, "%s /%s", dirname, ptr-> d_name); 
     ret = is_dir (chBuf); 
     if (0 == ret) 
     {   
       ret = delete_dir(chBuf); 
      if (0!=ret) 
       { 
         return -1; 
    } 
} 
    else if (1 == ret) 
     {  
      ret = remove (chBuf); 
     if (0!=ret)  
      { 
        return -1; 
    }  
  } 
}
  closedir (dir); 

  ret = remove (dirname); 
  if (0!= ret) 
   { 
    return -1; 
   } 
  return 0; 
 } 
}

Thanks !

You are missing a call to the function you implement: your main() functions does nothing except checking the argument count.

You need something like delete_dir(argv[1]); in the main function.

There is also a mistake with a space:

It need to be

snprintf (chBuf, 256, "%s/%s", dirname, ptr-> d_name);

instead of

snprintf (chBuf, 256, "%s /%s", dirname, ptr-> d_name);

Nesting functions is usually not a good style in C although it works with some compilers.

In general, a easy way to debug your code is add printf statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM