aboutsummaryrefslogtreecommitdiff
path: root/lib/common/mkdir_p.c
blob: 95187ba075a03b0d89bb40f6a12f9721e2a71ed1 (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * mkdir_p.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "common.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int mkdir_p(const char *path)
{
	size_t i, len;
	char *buffer;

	while (path[0] == '/' && path[1] == '/')
		++path;

	if (*path == '\0' || (path[0] == '/' && path[1] == '\0'))
		return 0;

	len = strlen(path) + 1;
	buffer = alloca(len);

	for (i = 0; i < len; ++i) {
		if (i > 0 && (path[i] == '/' || path[i] == '\0')) {
			buffer[i] = '\0';

			if (mkdir(buffer, 0755) != 0) {
				if (errno != EEXIST) {
					fprintf(stderr, "mkdir %s: %s\n",
						buffer, strerror(errno));
					return -1;
				}
			}
		}

		buffer[i] = path[i];
	}

	return 0;
}