Fix mkdir -p and allow -m to be specified along with -p

The mkdirp() function would not create the entire path but it just
happened to work because of the extra mkdir in the main loop.
This commit is contained in:
sin 2015-04-20 16:12:36 +01:00
parent 684b6fe8f2
commit d6885987e5

21
mkdir.c
View File

@ -11,17 +11,21 @@ mkdirp(char *path)
{ {
char *p; char *p;
for (p = path + (*path == '/'); *p; p++) { for (p = path; *p; p++) {
if (*p != '/') if (*p != '/')
continue; continue;
*p = '\0'; *p = '\0';
if (mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) { if (mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) {
weprintf("mkdir %s:", path); weprintf("mkdir %s:", path);
*p = '/';
return -1; return -1;
} }
*p = '/'; *p = '/';
} }
if (mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) {
weprintf("mkdir %s:", path);
return -1;
}
return 0; return 0;
} }
@ -54,14 +58,15 @@ main(int argc, char *argv[])
usage(); usage();
for (; *argv; argc--, argv++) { for (; *argv; argc--, argv++) {
if (pflag && mkdirp(*argv) < 0) { if (pflag) {
ret = 1; if (mkdirp(*argv) < 0)
} else if (mkdir(*argv, S_IRWXU | S_IRWXG | S_IRWXO) < 0) { ret = 1;
if (!(pflag && errno == EEXIST)) { } else if (mkdir(*argv, S_IRWXU | S_IRWXG | S_IRWXO) < 0 &&
errno != EEXIST) {
weprintf("mkdir %s:", *argv); weprintf("mkdir %s:", *argv);
ret = 1; ret = 1;
} }
} else if (mflag && chmod(*argv, mode) < 0) { if (mflag && chmod(*argv, mode) < 0) {
weprintf("chmod %s:", *argv); weprintf("chmod %s:", *argv);
ret = 1; ret = 1;
} }