mkdirp.c (791B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <sys/stat.h> 3 4 #include <errno.h> 5 #include <limits.h> 6 7 #include "../util.h" 8 9 int 10 mkdirp(const char *path) 11 { 12 mode_t mode, pmode, mask; 13 mask = umask(0); 14 mode = 0777 & ~mask; 15 pmode = 0777 & ( ~mask | 0300); 16 17 char tmp[PATH_MAX], *p; 18 struct stat st; 19 20 if (stat(path, &st) == 0) { 21 if (S_ISDIR(st.st_mode)) 22 return 0; 23 errno = ENOTDIR; 24 weprintf("%s:", path); 25 return -1; 26 } 27 28 estrlcpy(tmp, path, sizeof(tmp)); 29 for (p = tmp + (tmp[0] == '/'); *p; p++) { 30 if (*p != '/') 31 continue; 32 *p = '\0'; 33 if (mkdir(tmp, pmode) < 0 && errno != EEXIST) { 34 weprintf("mkdir %s:", tmp); 35 return -1; 36 } 37 *p = '/'; 38 } 39 if (mkdir(tmp, mode) < 0 && errno != EEXIST) { 40 weprintf("mkdir %s:", tmp); 41 return -1; 42 } 43 return 0; 44 }