Commit | Line | Data |
---|---|---|
8e68d1c8 DG |
1 | /* |
2 | * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca> | |
3 | * | |
4 | * This program is free software; you can redistribute it and/or | |
5 | * modify it under the terms of the GNU General Public License | |
82a3637f DG |
6 | * as published by the Free Software Foundation; only version 2 |
7 | * of the License. | |
8e68d1c8 DG |
8 | * |
9 | * This program is distributed in the hope that it will be useful, | |
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | * GNU General Public License for more details. | |
13 | * | |
14 | * You should have received a copy of the GNU General Public License | |
15 | * along with this program; if not, write to the Free Software | |
16 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. | |
17 | */ | |
18 | ||
19 | #define _GNU_SOURCE | |
20 | #include <errno.h> | |
21 | #include <limits.h> | |
22 | #include <stdio.h> | |
23 | #include <stdlib.h> | |
24 | #include <string.h> | |
25 | #include <sys/types.h> | |
26 | #include <sys/stat.h> | |
27 | #include <unistd.h> | |
28 | ||
29 | #include "utils.h" | |
30 | ||
b082db07 DG |
31 | /* |
32 | * get_home_dir | |
33 | * | |
34 | * Return pointer to home directory path using the env variable HOME. | |
35 | * No home, NULL is returned. | |
36 | */ | |
37 | const char *get_home_dir(void) | |
38 | { | |
39 | return ((const char *) getenv("HOME")); | |
40 | } | |
41 | ||
42 | /* | |
43 | * mkdir_recursive | |
44 | * | |
45 | * Create recursively directory using the FULL path. | |
46 | */ | |
8e68d1c8 DG |
47 | int mkdir_recursive(const char *path, mode_t mode) |
48 | { | |
49 | int ret; | |
50 | char *p, tmp[PATH_MAX]; | |
51 | size_t len; | |
52 | mode_t old_umask; | |
53 | ||
54 | ret = snprintf(tmp, sizeof(tmp), "%s", path); | |
55 | if (ret < 0) { | |
56 | perror("snprintf mkdir"); | |
57 | goto error; | |
58 | } | |
59 | ||
60 | len = ret; | |
61 | if (tmp[len - 1] == '/') { | |
62 | tmp[len - 1] = 0; | |
63 | } | |
64 | ||
65 | old_umask = umask(0); | |
66 | for (p = tmp + 1; *p; p++) { | |
67 | if (*p == '/') { | |
68 | *p = 0; | |
69 | ret = mkdir(tmp, mode); | |
70 | if (ret < 0) { | |
71 | if (!(errno == EEXIST)) { | |
72 | perror("mkdir recursive"); | |
73 | ret = errno; | |
74 | goto umask_error; | |
75 | } | |
76 | } | |
77 | *p = '/'; | |
78 | } | |
79 | } | |
80 | ||
81 | ret = mkdir(tmp, mode); | |
82 | if (ret < 0) { | |
83 | ret = errno; | |
84 | } | |
85 | ||
86 | umask_error: | |
87 | umask(old_umask); | |
88 | error: | |
89 | return ret; | |
90 | } |