Skip to content

Instantly share code, notes, and snippets.

@apofiget
Forked from Reobos/mkdir_p.c
Created May 3, 2017 13:42
Show Gist options
  • Save apofiget/72fe212a7634b59ef50beb28850f3539 to your computer and use it in GitHub Desktop.
Save apofiget/72fe212a7634b59ef50beb28850f3539 to your computer and use it in GitHub Desktop.
Simple recursive mkdir in C
/* recursive mkdir based on
http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#define PATH_MAX_STRING_SIZE 256
/* recursive mkdir */
int mkdir_p(const char *dir, const mode_t mode) {
char tmp[PATH_MAX_STRING_SIZE];
char *p = NULL;
struct stat sb;
size_t len;
/* copy path */
strncpy(tmp, dir, sizeof(tmp));
len = strlen(tmp);
if (len >= sizeof(tmp)) {
return -1;
}
/* remove trailing slash */
if(tmp[len - 1] == '/') {
tmp[len - 1] = 0;
}
/* recursive mkdir */
for(p = tmp + 1; *p; p++) {
if(*p == '/') {
*p = 0;
/* test path */
if (stat(tmp, &sb) != 0) {
/* path does not exist - create directory */
if (mkdir(tmp, mode) < 0) {
return -1;
}
} else if (!S_ISDIR(sb.st_mode)) {
/* not a directory */
return -1;
}
*p = '/';
}
}
/* test path */
if (stat(tmp, &sb) != 0) {
/* path does not exist - create directory */
if (mkdir(tmp, mode) < 0) {
return -1;
}
} else if (!S_ISDIR(sb.st_mode)) {
/* not a directory */
return -1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment