Skip to content

Instantly share code, notes, and snippets.

@Marneus68
Created May 1, 2012 20:59
Show Gist options
  • Save Marneus68/2571351 to your computer and use it in GitHub Desktop.
Save Marneus68/2571351 to your computer and use it in GitHub Desktop.
Recursive file and directory removal in C
int rm_r(const char* e_path)
{
DIR *dir = opendir(e_path);
struct dirent *ent;
if (dir == NULL)
/* error while opening the directory */
return -1;
/* DA MAGICKS */
while ((ent = readdir(dir)) != NULL)
{
if (strcmp(ent->d_name,".") != 0 && strcmp(ent->d_name,"..") != 0)
{
char temp_path[PATH_MAX];
strcpy(temp_path, e_path);
strcat(temp_path, "/");
strcat(temp_path, ent->d_name);
/* let's test if that entry is a file or a directory */
DIR *test_dir = opendir(temp_path);
if(test_dir)
/* it's a directory, let's remove all of it's content */
if (rm_r(temp_path) != 0) /* that's a recursive call */
return -1;
if (remove(temp_path) != 0)
return -1;
}
}
if (closedir(dir) != 0)
return -1;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment