Skip to content

Instantly share code, notes, and snippets.

@vincenthsu
Last active January 12, 2016 08:17
Show Gist options
  • Save vincenthsu/8a3f508331e48d9a2989 to your computer and use it in GitHub Desktop.
Save vincenthsu/8a3f508331e48d9a2989 to your computer and use it in GitHub Desktop.
recursive mkdir()
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