title: Recursive file delete in C on Linux
body: <p>I have a C program that, at one point in the program has this:</p>
  
  <p>system("rm -rf foo");</p>
  
  <p>Where foo is a directory.  I decided that, rather than calling system, it would be better to do the recursive delete right in the code.  I assumed a piece of code to do this would be easy to find.  Silly me.  Anyway, I ended up writing this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;dirent.h&gt;
  #include &lt;libgen.h&gt;
  
  int recursiveDelete(char* dirname) {
  
    DIR *dp;
    struct dirent *ep;
  
    char abs_filename[FILENAME_MAX];
  
    dp = opendir (dirname);
    if (dp != NULL)
      {
        while (ep = readdir (dp)) {
          struct stat stFileInfo;
  
          snprintf(abs_filename, FILENAME_MAX, "%s/%s", dirname, ep-&gt;d_name);
  
          if (lstat(abs_filename, &amp;stFileInfo) &lt; 0)
            perror ( abs_filename );
  
          if(S_ISDIR(stFileInfo.st_mode)) {
            if(strcmp(ep-&gt;d_name, ".") &amp;&amp; 
               strcmp(ep-&gt;d_name, "..")) {
              printf("%s directory\n",abs_filename);
              recursiveDelete(abs_filename);
            }
          } else {
            printf("%s file\n",abs_filename);
                    remove(abs_filename);
          }
            }
        (void) closedir (dp);
          }
    else
      perror ("Couldn't open the directory");
  
  
    remove(dirname);
    return 0;
  
  }
  </code></pre>
  
  <p>This seems to work, but I'm too scared to actually use it in production.  I'm sure I've done something wrong.  Does anyone know of a C library to do recursive delete I've missed, or can someone point out any mistakes I've made?  </p>
  
  <p>Thanks.</p>