micro-utils/coreutils/mkdir.c
Your Name d3fc1c1f88 fix
2023-10-30 18:09:33 +03:00

66 lines
1.0 KiB
C

#include <sys/stat.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int do_mkdir(const char *path) {
if (mkdir(path, 0777)) {
fprintf(stderr, "mkdir: %s %s\n", path, strerror(errno));
return 1;
}
return 0;
}
int do_parents(const char *path) {
if (path[0] == '.' || path[0] == '/')
return 0;
char *path2 = strdup(path);
if (!path2) {
fprintf(stderr, "mkdir: %s %s\n", path, strerror(errno));
return 1;
}
const char *par = dirname(path2);
do_parents(par);
do_mkdir(path2);
free(path2);
return 0;
}
int main(const int argc, const char **argv) {
unsigned int flag = 0;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-p"))
flag = 1;
else if (!strcmp(argv[i], "--help")) {
printf("mkdir [-p make parent dir] [dir1 dir2...]\n");
return 0;
}
}
for (; i < argc; i++) {
if (flag) {
if (do_parents(argv[i]))
return 1;
}
else {
if (do_mkdir(argv[i]))
return 1;
}
}
return 0;
}