1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 1997,2008 Oracle.  All rights reserved.
5 *
6 * $Id: mkpath.c,v 12.21 2008/01/12 13:42:35 bostic Exp $
7 */
8
9#include "db_config.h"
10
11#include "db_int.h"
12
13/*
14 * __db_mkpath -- --
15 *	Create intermediate directories.
16 *
17 * PUBLIC: int __db_mkpath __P((ENV *, const char *));
18 */
19int
20__db_mkpath(env, name)
21	ENV *env;
22	const char *name;
23{
24	size_t len;
25	int ret;
26	char *p, *t, savech;
27
28	/*
29	 * Get a copy so we can modify the string.  It's a path and potentially
30	 * quite long, so don't allocate the space on the stack.
31	 */
32	len = strlen(name) + 1;
33	if ((ret = __os_malloc(env, len, &t)) != 0)
34		return (ret);
35	memcpy(t, name, len);
36
37	/*
38	 * Cycle through the path, creating intermediate directories.
39	 *
40	 * Skip the first byte if it's a path separator, it's the start of an
41	 * absolute pathname.
42	 */
43	if (PATH_SEPARATOR[1] == '\0') {
44		for (p = t + 1; p[0] != '\0'; ++p)
45			if (p[0] == PATH_SEPARATOR[0]) {
46				savech = *p;
47				*p = '\0';
48				if (__os_exists(env, t, NULL) &&
49				    (ret = __os_mkdir(
50					env, t, env->dir_mode)) != 0)
51					break;
52				*p = savech;
53			}
54	} else
55		for (p = t + 1; p[0] != '\0'; ++p)
56			if (strchr(PATH_SEPARATOR, p[0]) != NULL) {
57				savech = *p;
58				*p = '\0';
59				if (__os_exists(env, t, NULL) &&
60				    (ret = __os_mkdir(
61					env, t, env->dir_mode)) != 0)
62					break;
63				*p = savech;
64			}
65
66	__os_free(env, t);
67	return (ret);
68}
69