Files
sbase/libutil/mkdirp.c
Michael Forney 6ac5f01cc9 mkdir -p: Fail if argument exists, but is not a directory
If it is a directory, we can just return straightaway.
2017-07-03 21:03:09 +02:00

40 lines
735 B
C

/* See LICENSE file for copyright and license details. */
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include "../util.h"
int
mkdirp(const char *path)
{
char tmp[PATH_MAX], *p;
struct stat st;
if (stat(path, &st) == 0) {
if (S_ISDIR(st.st_mode))
return 0;
errno = ENOTDIR;
weprintf("%s:", path);
return -1;
}
estrlcpy(tmp, path, sizeof(tmp));
for (p = tmp + (tmp[0] == '/'); *p; p++) {
if (*p != '/')
continue;
*p = '\0';
if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) {
weprintf("mkdir %s:", tmp);
return -1;
}
*p = '/';
}
if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) {
weprintf("mkdir %s:", tmp);
return -1;
}
return 0;
}