comparison recpt1/mkpath.c @ 61:f1553492e8bb

ensure path of destination file exists. imported Jonathan Leffler's mkpath.
author Yoshiki Yazawa <yaz@honeyplanet.jp>
date Fri, 09 Oct 2009 11:04:36 +0900
parents
children
comparison
equal deleted inserted replaced
60:181737b0533c 61:f1553492e8bb
1 /* mkpath is originally written by Jonathan Leffler.
2 * see "http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux" for detail.
3 * copyright: (C) JLSS 1990-91,1997-98,2001,2005,2008
4 */
5
6 #include <sys/stat.h>
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <errno.h>
11
12 static int
13 do_mkdir(const char *path, mode_t mode)
14 {
15 struct stat st;
16 int status = 0;
17
18 if (stat(path, &st) != 0) {
19 /* Directory does not exist */
20 if (mkdir(path, mode) != 0)
21 status = -1;
22 }
23 else if (!S_ISDIR(st.st_mode)) {
24 errno = ENOTDIR;
25 status = -1;
26 }
27
28 return(status);
29 }
30
31 int
32 mkpath(const char *path, mode_t mode)
33 {
34 char *pp;
35 char *sp;
36 int status;
37 char *copypath = strdup(path);
38
39 status = 0;
40 pp = copypath;
41 while (status == 0 && (sp = strchr(pp, '/')) != 0) {
42 if (sp != pp) {
43 /* Neither root nor double slash in path */
44 *sp = '\0';
45 status = do_mkdir(copypath, mode);
46 *sp = '/';
47 }
48 pp = sp + 1;
49 }
50 if (status == 0)
51 status = do_mkdir(path, mode);
52 free(copypath);
53 return (status);
54 }