summaryrefslogtreecommitdiffstats
path: root/lib/make_directory.c
blob: 29d08cf536c74882da162b411c192d55fb54883e (plain)
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

#include <string.h>
#include <errno.h>
#ifdef __BAREBOX__
#include <fs.h>
#include <libfile.h>
#include <malloc.h>
#include <common.h>
#define STATIC
#else
#define STATIC static inline
#endif

STATIC int make_directory(const char *dir)
{
	char *s = strdup(dir);
	char *path = s;
	char c;
	int ret = 0;

	do {
		c = 0;

		/* Bypass leading non-'/'s and then subsequent '/'s. */
		while (*s) {
			if (*s == '/') {
				do {
					++s;
				} while (*s == '/');
				c = *s;		/* Save the current char */
				*s = 0;		/* and replace it with nul. */
				break;
			}
			++s;
		}

		if (mkdir(path, 0777) < 0) {

			/* If we failed for any other reason than the directory
			 * already exists, output a diagnostic and return -1.*/
			if (errno != EEXIST) {
				ret = -errno;
				break;
			}
		}
		if (!c)
			goto out;

		/* Remove any inserted nul from the path (recursive mode). */
		*s = c;

	} while (1);

out:
	free(path);
	if (ret)
		errno = -ret;
	return ret;
}
#ifdef __BAREBOX__
EXPORT_SYMBOL(make_directory);
#endif