-
Notifications
You must be signed in to change notification settings - Fork 0
/
c_mkpath.c.1
79 lines (55 loc) · 1.44 KB
/
c_mkpath.c.1
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Recursive mkdir
Source:
https://gist.github.com/JonathonReinhart/8c0d90191c38af2dcadb102c4e202950
*/
#include <string.h>
//#include <limits.h> // PATH_MAX ? where is it ? or _POSIX_PATH_MAX ?
#include <linux/limits.h>
// #include <linux/limits.h>
// --> /usr/include/linux/limits.h
// --> PATH_MAX = 4096
// #include <limits.h>
//#ifdef __USE_POSIX
//# include <bits/posix1_lim.h>
//#endif
// --> /usr/include/limits.h ->
// --> /usr/include/x86_64-linux-gnu/bits/posix1_lim.h
// Number of bytes in a pathname.
// #define _POSIX_PATH_MAX 256
#include <sys/stat.h> // mkdir(2)
#include <errno.h>
int c_mkpath ( const char *path, mode_t mode )
{
// Adapted from http://stackoverflow.com/a/2336245/119527
const size_t len = strlen ( path );
char path_trim [ PATH_MAX ] ;
char *p ;
errno = 0 ;
// Copy string so its mutable
if ( len > sizeof(path_trim) - 1 )
{
errno = ENAMETOOLONG;
return -1;
}
strcpy ( path_trim, path ) ;
// Iterate the string
for ( p = path_trim + 1; *p; p++ )
{
if ( *p == '/' )
{
// Temporarily truncate
*p = '\0';
if ( mkdir( path_trim, mode ) != 0)
{
if (errno != EEXIST) return -1 ;
}
*p = '/';
}
}
if ( mkdir ( path_trim, mode ) != 0 )
{
if ( errno != EEXIST ) return -1 ;
}
return 0;
}