Skip to content

Instantly share code, notes, and snippets.

@kala13x
Created January 3, 2016 21:34
Show Gist options
  • Save kala13x/e877d24fd5bfb0d5f135 to your computer and use it in GitHub Desktop.
Save kala13x/e877d24fd5bfb0d5f135 to your computer and use it in GitHub Desktop.
Recursively remove directory.
/*
* Recursively remove directory with the given path.
*
* Copyright (c) 2015 Sun Dro (a.k.a. 7th Ghost)
* Web: http://off-sec.com/ ; E-Mail: [email protected]
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
/*
* remove_directory - Recursively remove directory. Argument
* path is the directory path. On success, zero is returned.
* On error, -1 is returned and errno is set appropriately.
*/
int remove_directory(const char *path)
{
/* Check if path exists */
struct stat statbuf = {0};
int retval = stat(path, &statbuf);
if (retval < 0) return -1;
/* Open directory */
DIR *dir = opendir(path);
if (dir)
{
size_t path_len = strlen(path);
struct dirent *entry;
retval = 0;
while (!retval && (entry = readdir(dir)))
{
int xretval = -1;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
/* Allocate path buffer memory */
size_t len = path_len + strlen(entry->d_name) + 2;
char *buf = (char*)malloc(len);
if (buf)
{
snprintf(buf, len, "%s/%s", path, entry->d_name);
if (!stat(buf, &statbuf))
{
/* Check its directory or not */
if (S_ISDIR(statbuf.st_mode)) xretval = remove_directory(buf);
else xretval = unlink(buf);
}
/* Cleanup allocated memory */
free(buf);
}
retval = xretval;
}
/* Close dir pointer */
closedir(dir);
}
if (!retval)
retval = rmdir(path);
return retval;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s <directory>\n", argv[0]);
printf("Example: %s /home/temp\n", argv[0]);
exit(0);
}
if (remove_directory(argv[1]) < 0)
printf("%s\n", strerror(errno));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment