Last active
January 12, 2016 08:17
-
-
Save vincenthsu/8a3f508331e48d9a2989 to your computer and use it in GitHub Desktop.
recursive mkdir()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int recursive_mkdir(const char *dir, mode_t mode) | |
{ | |
assert(dir && *dir); | |
// already exist | |
if (access(dir, F_OK) == 0) { | |
return 0; | |
} | |
size_t len; | |
len = strlen(dir); | |
char* tmp = (char*) malloc(len); | |
strcpy(tmp, dir); | |
if (tmp[len - 1] == '/') | |
tmp[len - 1] = '\0'; | |
char *p = NULL; | |
for (p = tmp + 1; *p; p++) { | |
if (*p == '/') { | |
*p = 0; | |
if (mkdir(tmp, mode) == -1) { | |
if (errno != EEXIST) { | |
return -1; | |
} | |
} | |
*p = '/'; | |
} | |
} | |
// No need to check existence here, because we've checked at start. | |
if (mkdir(tmp, mode) == -1) | |
return -1; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment