summaryrefslogtreecommitdiff
path: root/src/common/mkpath.c
blob: 163dbfba07b2aa28dd0a9234991312a6f1fa8f9d (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
63
64
65
66
67
68
/*-
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 1997, 2015 Oracle and/or its affiliates.  All rights reserved.
 *
 * $Id$
 */

#include "db_config.h"

#include "db_int.h"

/*
 * __db_mkpath -- --
 *	Create intermediate directories.
 *
 * PUBLIC: int __db_mkpath __P((ENV *, const char *));
 */
int
__db_mkpath(env, name)
	ENV *env;
	const char *name;
{
	size_t len;
	int ret;
	char *p, *t, savech;

	/*
	 * Get a copy so we can modify the string.  It's a path and potentially
	 * quite long, so don't allocate the space on the stack.
	 */
	len = strlen(name) + 1;
	if ((ret = __os_malloc(env, len, &t)) != 0)
		return (ret);
	memcpy(t, name, len);

	/*
	 * Cycle through the path, creating intermediate directories.
	 *
	 * Skip the first byte if it's a path separator, it's the start of an
	 * absolute pathname.
	 */
	if (PATH_SEPARATOR[1] == '\0') {
		for (p = t + 1; p[0] != '\0'; ++p)
			if (p[0] == PATH_SEPARATOR[0]) {
				savech = *p;
				*p = '\0';
				if (__os_exists(env, t, NULL) &&
				    (ret = __os_mkdir(
					env, t, env->dir_mode)) != 0)
					break;
				*p = savech;
			}
	} else
		for (p = t + 1; p[0] != '\0'; ++p)
			if (strchr(PATH_SEPARATOR, p[0]) != NULL) {
				savech = *p;
				*p = '\0';
				if (__os_exists(env, t, NULL) &&
				    (ret = __os_mkdir(
					env, t, env->dir_mode)) != 0)
					break;
				*p = savech;
			}

	__os_free(env, t);
	return (ret);
}