code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <string.h>
#include <limits.h> /* PATH_MAX */
#include <sys/stat.h> /* mkdir(2) */
#include <errno.h>

int mkdir_recursive(const string &path) {
const size_t len = path.length();
char _path[PATH_MAX];
char *p;

errno = 0;

/* Copy string so its mutable */
if (len > sizeof(_path) - 1) {
errno = ENAMETOOLONG;
return -1;
}
strcpy(_path, path.c_str());

/* Iterate the string */
for (p = _path + 1; *p; p++) {
if (*p == '/') {
/* Temporarily truncate */
*p = '\0';

if (mkdir(_path, S_IRWXU) != 0) {
if (errno != EEXIST)
return -1;
}

*p = '/';
}
}

if (mkdir(_path, S_IRWXU) != 0) {
if (errno != EEXIST)
return -1;
}

return 0;
}