]> git.sur5r.net Git - i3/i3/blob - libi3/mkdirp.c
Remove redundant NULL check
[i3/i3] / libi3 / mkdirp.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include "libi3.h"
9
10 #include <errno.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/stat.h>
14
15 /*
16  * Emulates mkdir -p (creates any missing folders)
17  *
18  */
19
20 #if !defined(__sun)
21 int mkdirp(const char *path, mode_t mode) {
22     if (mkdir(path, mode) == 0)
23         return 0;
24     if (errno == EEXIST) {
25         struct stat st;
26         /* Check that the named file actually is a directory. */
27         if (stat(path, &st)) {
28             ELOG("stat(%s) failed: %s\n", path, strerror(errno));
29             return -1;
30         }
31         if (!S_ISDIR(st.st_mode)) {
32             ELOG("mkdir(%s) failed: %s\n", path, strerror(ENOTDIR));
33             return -1;
34         }
35         return 0;
36     } else if (errno != ENOENT) {
37         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
38         return -1;
39     }
40     char *copy = sstrdup(path);
41     /* strip trailing slashes, if any */
42     while (copy[strlen(copy) - 1] == '/')
43         copy[strlen(copy) - 1] = '\0';
44
45     char *sep = strrchr(copy, '/');
46     if (sep == NULL) {
47         free(copy);
48         return -1;
49     }
50     *sep = '\0';
51     int result = -1;
52     if (mkdirp(copy, mode) == 0)
53         result = mkdirp(path, mode);
54     free(copy);
55
56     return result;
57 }
58 #endif