micro-utils/coreutils/mkdir.c
2023-11-07 16:21:46 +03:00

69 lines
1.0 KiB
C

#include <sys/stat.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.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(int argc, char **argv) {
unsigned int p_flag = 0;
int opt;
while ((opt = getopt(argc, argv, "p")) != -1) {
switch (opt) {
case 'p':
p_flag = 1;
break;
default:
printf("mkdir [dst1 dst2...]\n\t[-p Make parent dir]\n");
return 0;
}
}
argv += optind;
argc -= optind;
for (int i = 0; i < argc; i++) {
if (p_flag) {
if (do_parents(argv[i]))
return 1;
}
else {
if (do_mkdir(argv[i]))
return 1;
}
}
return 0;
}