Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. int remove_directory(const char *path)
  2. {
  3.    DIR *d = opendir(path);
  4.    size_t path_len = strlen(path);
  5.    int r = -1;
  6.  
  7.    if (d)
  8.    {
  9.       struct dirent *p;
  10.  
  11.       r = 0;
  12.  
  13.       while (!r && (p=readdir(d)))
  14.       {
  15.           int r2 = -1;
  16.           char *buf;
  17.           size_t len;
  18.  
  19.           /* Skip the names "." and ".." as we don't want to recurse on them. */
  20.           if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
  21.           {
  22.              continue;
  23.           }
  24.  
  25.           len = path_len + strlen(p->d_name) + 2;
  26.           buf = malloc(len);
  27.  
  28.           if (buf)
  29.           {
  30.              struct stat statbuf;
  31.  
  32.              snprintf(buf, len, "%s/%s", path, p->d_name);
  33.  
  34.              if (!stat(buf, &statbuf))
  35.              {
  36.                 if (S_ISDIR(statbuf.st_mode))
  37.                 {
  38.                    r2 = remove_directory(buf);
  39.                 }
  40.                 else
  41.                 {
  42.                    r2 = unlink(buf);
  43.                 }
  44.              }
  45.  
  46.              free(buf);
  47.           }
  48.  
  49.           r = r2;
  50.       }
  51.  
  52.       closedir(d);
  53.    }
  54.  
  55.    if (!r)
  56.    {
  57.       r = rmdir(path);
  58.    }
  59.  
  60.    return r;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement