micro-utils/coreutils/rm.c

98 lines
1.7 KiB
C
Raw Normal View History

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
2023-10-31 12:53:32 +03:00
#include "make_path.h"
#include "get_stat.h"
2023-10-30 18:09:33 +03:00
unsigned int f_flag;
int rmtree(const char *path) {
struct stat stat_path;
2023-10-31 12:53:32 +03:00
if (mu_get_lstat("rm", path, &stat_path))
2023-10-20 18:29:50 +03:00
return 1;
2023-10-20 18:29:50 +03:00
if (!S_ISDIR(stat_path.st_mode) || S_ISLNK(stat_path.st_mode)) {
if (unlink(path) < 0) {
2023-10-30 18:09:33 +03:00
if (!f_flag)
fprintf(stderr, "rm: %s: is not directory\n", path);
2023-10-16 20:57:30 +03:00
return 1;
}
return 0;
}
DIR *dir = opendir(path);
if (dir == NULL) {
2023-10-30 18:09:33 +03:00
if (!f_flag)
fprintf(stderr, "rm: %s: Can`t open directory\n", path);
2023-10-16 20:57:30 +03:00
return 1;
}
2023-11-01 14:17:25 +03:00
int ret = 0;
struct dirent *ep;
while ((ep = readdir(dir)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
2023-10-31 12:53:32 +03:00
char *full_path = mu_make_path("rm", path, ep->d_name);
2023-10-21 15:05:49 +03:00
if (full_path == NULL)
continue;
2023-11-01 14:17:25 +03:00
if (rmtree(full_path))
ret = 1;
free(full_path);
}
closedir(dir);
if (rmdir(path) < 0)
2023-10-30 18:09:33 +03:00
if (!f_flag)
fprintf(stderr, "rm: %s: can`t remove a directory\n", path);
2023-11-01 14:17:25 +03:00
return ret;
}
2023-11-06 23:52:48 +03:00
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "frR")) != -1) {
switch (opt) {
case 'f':
f_flag = 1;
break;
case 'r':
case 'R':
break;
default:
2023-11-07 16:21:46 +03:00
printf("rm [file1 file2...]\n\t[-f Force]\n");
2023-11-06 23:52:48 +03:00
return 0;
2023-10-30 18:09:33 +03:00
}
}
2023-11-06 23:52:48 +03:00
if (argv[optind] == NULL) {
fprintf(stderr, "rm: missing operand\n");
return 1;
}
argv += optind;
argc -= optind;
int ret = 0;
for (int i = 0; i < argc; i++) {
2023-10-30 18:09:33 +03:00
if (!strcmp(argv[i], ".") || !strcmp(argv[i], "..")){
printf("rm: refusing to remove '.' or '..' directory\n");
break;
}
2023-10-20 17:32:50 +03:00
2023-11-06 23:52:48 +03:00
if (rmtree(argv[i]))
ret = 1;
}
2023-11-06 23:52:48 +03:00
return ret;
}
2023-10-16 20:57:30 +03:00