+/*
+ * mkdir_p, a very simple `mkdir -p` implementation in C
+ * Copyright (C) 2016 Rafał Długołęcki
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "mkdir_p.h"
+
+int mkdir_p(const char *pathname, mode_t mode)
+{
+ int i = 0;
+ int error = 0;
+ char * path = NULL;
+ int len = 0;
+
+ if (pathname == NULL) {
+ return -1;
+ }
+
+ len = strlen(pathname);
+
+ if (pathname[0] == MKDIR_P_SEPARATOR) {
+ i = 1;
+ }
+
+ while ((i <= len) && !error) {
+ if ((i + 1 < len) && (pathname[i + 1] == MKDIR_P_SEPARATOR)) {
+ path = malloc(sizeof(char) * (i + 2));
+ strncpy(path, pathname, i + 1);
+ path[i + 1] = '\0';
+ }
+ else if ((i + 1 == len) && (pathname[i] != MKDIR_P_SEPARATOR)) {
+ path = malloc(sizeof(char) * (i + 2));
+ strncpy(path, pathname, i + 1);
+ path[i + 1] = '\0';
+ }
+
+
+ if (path != NULL) {
+ error = mkdir(path, mode);
+
+ if ((error != 0) && (errno != EEXIST)) {
+ perror("Unable to create directory");
+ }
+ else {
+ error = 0;
+ }
+
+ free(path);
+ path = NULL;
+ }
+ i++;
+ }
+
+ return error;
+}
+
+#ifdef _MKDIR_P_STANDALONE
+
+int main(int argc, char ** argv)
+{
+ if (argc == 2) {
+ return mkdir_p(argv[1], 0700);
+ }
+ else {
+ puts("mkdir_p, a very simple `mkdir -p` implementation in C");
+ puts("Version: " MKDIR_P_VERSION);
+ puts("\n\tUsage: mkdir_p PATH\n\n");
+ }
+
+ return 0;
+}
+
+#endif /* _MKDIR_P_STANDALONE */