mkdirp.c (725B)
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, mode_t mode, mode_t pmode) 11 { 12 char tmp[PATH_MAX], *p; 13 struct stat st; 14 15 if (stat(path, &st) == 0) { 16 if (S_ISDIR(st.st_mode)) 17 return 0; 18 errno = ENOTDIR; 19 return -1; 20 } 21 22 if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp)) { 23 errno = ENAMETOOLONG; 24 return -1; 25 } 26 for (p = tmp + (tmp[0] == '/'); *p; p++) { 27 if (*p != '/') 28 continue; 29 *p = '\0'; 30 if (mkdir(tmp, pmode) < 0 && errno != EEXIST) 31 return -1; 32 *p = '/'; 33 } 34 if (mkdir(tmp, mode) < 0 && errno != EEXIST) 35 return -1; 36 return 0; 37 }