Created
May 3, 2011 17:31
-
-
Save EmilHernvall/953783 to your computer and use it in GitHub Desktop.
Function for creating all the folders in a path automatically
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <errno.h> | |
int mkdirp(const char *path, mode_t mode) | |
{ | |
char *pos, *base; | |
char **dirs; | |
int i, len, dircount, res; | |
// Count the number of directories in path | |
dircount = 0; | |
for (i = 0; path[i] != '\0'; i++) { | |
if (path[i] == '/') { | |
dircount++; | |
} | |
} | |
/* | |
Break down path backwards and store the result in | |
an array. | |
For example, for path = /foo/bar/baz we get: | |
/foo/bar | |
/foo | |
*/ | |
base = (char*)path; | |
dirs = (char**)malloc(sizeof(char*) * (dircount+1)); | |
memset(dirs, '\0', sizeof(char*) * (dircount+1)); | |
i = 0; | |
while ((pos = strrchr(base, '/')) != NULL) { | |
len = pos - base; | |
if (len == 0) { | |
dirs[i] = NULL; | |
break; | |
} | |
dirs[i] = (char*)malloc(sizeof(char*) * (len + 1)); | |
strncpy(dirs[i], base, len); | |
dirs[i][len] = '\0'; | |
base = dirs[i]; | |
i++; | |
} | |
// Save the number of real directories found | |
dircount = i; | |
// Create the directories | |
res = 0; | |
for (; i >= 0; i--) { | |
if (dirs[i] == NULL) { | |
continue; | |
} | |
if (!mkdir(dirs[i], mode)) { | |
continue; | |
} | |
if (errno == EEXIST) { | |
continue; | |
} | |
res = -1; | |
break; | |
} | |
// If the path didn't end with /, the last directory got dropped | |
// and wasn't created | |
if (mkdir(path, mode)) { | |
res = -1; | |
} | |
// Free used memory | |
for (i = 0; i < dircount; i++) { | |
if (dirs[i] == NULL) { | |
continue; | |
} | |
free(dirs[i]); | |
} | |
free(dirs); | |
return res; | |
} | |
int main(int argc, char** argv) | |
{ | |
if (argc != 2) { | |
return 1; | |
} | |
if (mkdirp(argv[1], 0777) == -1) { | |
perror("mkdirp"); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment