libite 2.6.1
makepath.c
Go to the documentation of this file.
1/* mkpath() -- Create all components leading up to a given directory
2 *
3 * Copyright (c) 2013-2021 Joachim Wiberg <troglobit@gmail.com>
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
24
25#include <errno.h>
26#include <libgen.h>
27#include <stdarg.h>
28#include <stdlib.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include "lite.h"
32
40int mkpath(const char *dir, mode_t mode)
41{
42 struct stat sb;
43
44 if (!dir) {
45 errno = EINVAL;
46 return -1;
47 }
48
49 if (!stat(dir, &sb))
50 return 0;
51
52 mkpath(dirname(strdupa(dir)), mode);
53
54 return mkdir(dir, mode);
55}
56
66int fmkpath(mode_t mode, const char *fmt, ...)
67{
68 va_list ap;
69 char *path;
70 int len;
71
72 va_start(ap, fmt);
73 len = vsnprintf(NULL, 0, fmt, ap);
74 va_end(ap);
75
76 path = alloca(len + 1);
77 if (!path) {
78 errno = ENOMEM;
79 return -1;
80 }
81
82 va_start(ap, fmt);
83 len = vsnprintf(path, len + 1, fmt, ap);
84 va_end(ap);
85
86 return mkpath(path, mode);
87}
88
105int makepath(const char *dir)
106{
107 return mkpath(dir, 0777);
108}
109
int dir(const char *dir, const char *type, int(*filter)(const char *file), char ***list, int strip)
Definition dir.c:82
int makepath(const char *dir)
Definition makepath.c:105
int mkpath(const char *dir, mode_t mode)
Definition makepath.c:40
int fmkpath(mode_t mode, const char *fmt,...)
Definition makepath.c:66