Implement recursion using nftw.

FTW_DEPTH gives the natural file removal order, but it doesn't lend
itself easily well to traversing the directory tree in a multi-threaded
manner.
This commit is contained in:
Érico Nogueira 2021-05-17 23:44:56 -03:00
parent 4bdc7f18c5
commit f3f90857e8
1 changed files with 24 additions and 2 deletions

26
erm.c
View File

@ -1,4 +1,6 @@
#define _XOPEN_SOURCE 500 /* nftw */
#include <errno.h>
#include <ftw.h>
#include <stdbool.h>
#include <stdnoreturn.h>
#include <stdio.h>
@ -6,7 +8,17 @@
#include <string.h>
#include <unistd.h>
noreturn void usage(int s)
static int ftw_cb(const char *fpath, const struct stat *sb,
int typeflag, struct FTW *ftwbuf)
{
int rv;
if (typeflag == FTW_D || typeflag == FTW_DP) rv = rmdir(fpath);
else rv = unlink(fpath);
return rv;
}
noreturn static void usage(int s)
{
puts("erm [-reh] [files]");
exit(s);
@ -37,7 +49,17 @@ int main(int argc, char **argv)
int rv = 0;
if (recursive) {
/* TODO: descend */
for (int i = 0; i < argc; i++) {
char *path = argv[i];
if (nftw(path, ftw_cb, 40, FTW_DEPTH | FTW_PHYS)) {
fprintf(stderr, "failed to delve into '%s': %s\n", path, strerror(errno));
if (stop_at_error) {
return 1;
} else {
rv = 1;
}
}
}
} else {
for (int i = 0; i < argc; i++) {
char *path = argv[i];