75 lines
1.4 KiB
C
75 lines
1.4 KiB
C
#include <stdio.h>
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <dirent.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
|
|
int get_stat(const char *path, struct stat *stat_path) {
|
|
if (stat(path, stat_path)) {
|
|
fprintf(stderr, "rm: unable to stat %s: %s\n", path, strerror(errno));
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int rmtree(const char *path) {
|
|
struct stat stat_path;
|
|
get_stat(path, &stat_path);
|
|
|
|
if (S_ISDIR(stat_path.st_mode) == 0) {
|
|
if (unlink(path) < 0) {
|
|
fprintf(stderr, "rm: %s: is not directory\n", path);
|
|
return -1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
DIR *dir = opendir(path);
|
|
if (dir == NULL) {
|
|
fprintf(stderr, "rm: %s: Can`t open directory\n", path);
|
|
return -1;
|
|
}
|
|
|
|
struct dirent *ep;
|
|
while ((ep = readdir(dir)) != NULL) {
|
|
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
|
|
continue;
|
|
|
|
char *full_path = malloc(strlen(path) + strlen(ep->d_name) + 1);
|
|
if (full_path == NULL) {
|
|
fprintf(stderr, "rm: malloc() returned NULL\n");
|
|
return 1;
|
|
}
|
|
|
|
sprintf(full_path, "%s/%s", path, ep->d_name);
|
|
|
|
rmtree(full_path);
|
|
free(full_path);
|
|
}
|
|
|
|
closedir(dir);
|
|
if (rmdir(path) < 0)
|
|
fprintf(stderr, "rm: %s: can`t remove a directory\n", path);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int main(const int argc, char **argv) {
|
|
if (argc == 1) {
|
|
printf("rm: missing operand\n");
|
|
return 1;
|
|
}
|
|
|
|
for (int i = 1; i < argc; i++) {
|
|
int status = rmtree(argv[i]);
|
|
if (status != 0)
|
|
return status;
|
|
}
|
|
|
|
return 0;
|
|
}
|