micro-utils/coreutils/rm.c

84 lines
1.5 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;
}
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;
rmtree(full_path);
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);
return 0;
}
int main(const int argc, char **argv) {
2023-10-30 18:09:33 +03:00
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-f"))
f_flag = 1;
else if (!strcmp(argv[i], "--help")) {
printf("rm [-f force] [src1 src2...]\n");
return 0;
}
}
2023-10-24 20:23:32 +03:00
int status = 0;
2023-10-30 18:09:33 +03:00
for (; i < argc; i++) {
if (!strcmp(argv[i], ".") || !strcmp(argv[i], "..")){
printf("rm: refusing to remove '.' or '..' directory\n");
break;
}
2023-10-20 17:32:50 +03:00
int status = rmtree(argv[i]);
if (status != 0)
2023-10-24 20:23:32 +03:00
status = 1;
}
2023-10-24 20:23:32 +03:00
return status;
}
2023-10-16 20:57:30 +03:00