micro-utils/src/rm.c

121 lines
1.9 KiB
C
Raw Normal View History

2024-07-01 10:23:00 +00:00
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <ctype.h>
#include "make_path.h"
#include "get_stat.h"
#include "recurse.h"
#include "unused.h"
2024-07-09 12:43:55 +00:00
static char *f_flag = "rm";
static char r_flag;
2024-07-13 16:36:14 +00:00
static char i_flag;
2024-07-09 12:43:55 +00:00
static char v_flag;
2024-07-01 10:23:00 +00:00
2024-07-09 12:43:55 +00:00
static int verbose(const char *path) {
2024-07-13 16:36:14 +00:00
if (i_flag) {
2024-07-01 10:23:00 +00:00
fprintf(stderr, "rm: remove %s? [y/n] ", path);
fflush(stderr);
int c = 0;
int key = 0;
while ((c = fgetc(stdin)) != EOF && c != '\n') {
if (c == 'y')
key = 1;
}
return key;
}
2024-07-13 16:36:14 +00:00
else if (v_flag && f_flag)
fprintf(stderr, "rm: removing %s\n", path);
2024-07-01 10:23:00 +00:00
return 1;
}
2024-07-09 12:43:55 +00:00
static void handle_error(const char *path) {
2024-07-01 10:23:00 +00:00
if (f_flag)
fprintf(stderr, "rm: %s: %s\n", path, strerror(errno));
}
2024-07-09 12:43:55 +00:00
static int rm(const char *path, void *p) {
2024-07-01 10:23:00 +00:00
UNUSED(p);
if (verbose(path) && remove(path) < 0) {
handle_error(path);
return 1;
}
return 0;
}
2024-07-09 12:43:55 +00:00
static int rmd(const char *path, void *p) {
2024-07-01 10:23:00 +00:00
UNUSED(p);
if (verbose(path) && rmdir(path) < 0) {
handle_error(path);
return 1;
}
return 0;
}
int main(int argc, char **argv) {
int opt;
2024-07-13 16:36:14 +00:00
while ((opt = getopt(argc, argv, "friv")) != -1) {
2024-07-01 10:23:00 +00:00
switch (opt) {
case 'f':
f_flag = NULL;
break;
case 'r':
r_flag = 1;
break;
case 'i':
2024-07-13 16:36:14 +00:00
i_flag = 1;
break;
case 'v':
2024-07-01 10:23:00 +00:00
v_flag = 1;
break;
default:
2024-07-13 16:36:14 +00:00
puts("rm [friv] [file1 file2/dir...]\n\t-f Never prompt\n\t-r Recursive\n\t-i Print prompt before remove\n\t-v Verbose");
2024-07-01 10:23:00 +00:00
return 0;
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
fprintf(stderr, "rm: missing operand\n");
return 1;
}
int ret = 0;
for (int i = 0; i < argc; i++) {
if (!strcmp(argv[i], ".") || !strcmp(argv[i], "..")){
printf("rm: refusing to remove '.' or '..' directory\n");
break;
}
if (r_flag) {
if (mu_recurse(f_flag, 1, argv[i], NULL, rm, rmd))
ret = 1;
}
else
if (rm(argv[i], NULL))
ret = 1;
}
return ret;
}