2 * mkdir_p, a very simple `mkdir -p` implementation in C
3 * Copyright (C) 2016 Rafał Długołęcki
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
20 #include <sys/types.h>
24 int mkdir_p(const char *pathname, mode_t mode)
31 if (pathname == NULL) {
35 len = strlen(pathname);
37 if (pathname[0] == MKDIR_P_SEPARATOR) {
41 while ((i <= len) && !error) {
42 if ((i + 1 < len) && (pathname[i + 1] == MKDIR_P_SEPARATOR)) {
43 path = malloc(sizeof(char) * (i + 2));
44 strncpy(path, pathname, i + 1);
47 else if ((i + 1 == len) && (pathname[i] != MKDIR_P_SEPARATOR)) {
48 path = malloc(sizeof(char) * (i + 2));
49 strncpy(path, pathname, i + 1);
55 error = mkdir(path, mode);
57 if ((error != 0) && (errno != EEXIST)) {
58 perror("Unable to create directory");
73 #ifdef _MKDIR_P_STANDALONE
75 int main(int argc, char ** argv)
78 return mkdir_p(argv[1], 0700);
81 puts("mkdir_p, a very simple `mkdir -p` implementation in C");
82 puts("Version: " MKDIR_P_VERSION);
83 puts("\n\tUsage: mkdir_p PATH\n\n");
89 #endif /* _MKDIR_P_STANDALONE */