-
Notifications
You must be signed in to change notification settings - Fork 15
/
mkdirs.c
66 lines (55 loc) · 1.05 KB
/
mkdirs.c
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
/*
* Copyright (c) 2003 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
*/
#include "config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include "mkdirs.h"
/*
* The right most element of the path is assumed to be a file.
*/
int
mkdirs( char *path )
{
char *p, *q = NULL;
int saved_errno;
saved_errno = errno;
/* try making longest path first, working backward */
for (;;) {
if (( p = strrchr( path, '/' )) == NULL ) {
errno = EINVAL;
return( -1 );
}
*p = '\0';
if ( q != NULL ) {
*q = '/';
}
if ( mkdir( path, 0777 ) == 0 ) {
break;
}
if ( errno == EEXIST ) {
break;
} else if ( errno != ENOENT ) {
return( -1 );
}
q = p;
}
*p = '/';
if ( q != NULL ) {
p++;
for ( p = strchr( p, '/' ); p != NULL; p = strchr( p, '/' )) {
*p = '\0';
if ( mkdir( path, 0777 ) < 0 ) {
if ( errno != EEXIST ) {
return( -1 );
}
}
*p++ = '/';
}
}
errno = saved_errno;
return( 0 );
}