Skip to content

Instantly share code, notes, and snippets.

@michaelmelanson
Created September 10, 2009 10:16
Show Gist options
  • Save michaelmelanson/184461 to your computer and use it in GitHub Desktop.
Save michaelmelanson/184461 to your computer and use it in GitHub Desktop.
Recursively deletes a directory and all its contents, like "rmdir -Rf" on the command line
/*
* Recursively deletes a directory, like "rm -Rf" on the command-line.
*
* Returns 0 on success. On error, returns -1 and sets errno.
*/
int rmdir_r(const char *dirname)
{
struct dirent **namelist;
int n = scandir(dirname, &namelist, 0, alphasort);
if (n < 0) {
return -1;
} else {
for (int i = 0; i < n; ++i) {
// skip special entries
if (strcmp(namelist[i]->d_name, ".") == 0 ||
strcmp(namelist[i]->d_name, "..") == 0) {
continue;
}
// get a path to this file, relative to the current working directory
char *filename;
asprintf(&filename, "%s/%s", dirname, namelist[i]->d_name);
// what sort of file is this anyways?
struct stat st;
if (lstat(filename, &st)) {
return -1;
}
if (S_ISDIR(st.st_mode)) {
// recursively delete directories
if (rmdir_r(filename)) {
return -1;
}
} else {
// unlink files
if (unlink(filename)) {
return -1;
}
}
// clean up our messes
free(filename);
}
// the directory should now be empty, so delete it
if (rmdir(dirname)) {
return -1;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment