Skip to content

Instantly share code, notes, and snippets.

@zonque
Created June 17, 2019 09:03
Show Gist options
  • Save zonque/6edb10757e73addeecb97bedfae91392 to your computer and use it in GitHub Desktop.
Save zonque/6edb10757e73addeecb97bedfae91392 to your computer and use it in GitHub Desktop.
Very minimal implementation of a recursive 'rm' in plain C
/*
* Very minimal implementation of a recursive 'rm'.
*
* gcc -Wall -o rm-rf rm-rf.c
*
* License: MIT
*/
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
static void rm_rf_at(int basefd, const char *basepath) {
struct dirent *de;
int fd;
DIR *d;
fd = openat(basefd, basepath, O_DIRECTORY);
if (fd < 0)
return;
d = fdopendir(fd);
if (d == NULL) {
close(fd);
return;
}
while ((de = readdir(d))) {
if ((strcmp(de->d_name, ".") == 0) || (strcmp(de->d_name, "..") == 0))
continue;
switch (de->d_type) {
case DT_DIR:
rm_rf_at(fd, de->d_name);
break;
default:
unlinkat(fd, de->d_name, 0);
break;
}
}
close(fd);
unlinkat(basefd, basepath, AT_REMOVEDIR);
}
static void rm_rf(const char *basepath) {
rm_rf_at(AT_FDCWD, basepath);
}
int main(void) {
rm_rf("test");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment