/* * MKDIRPATH.C * * (c)Copyright 2015, Matthew Dillon, All Rights Reserved. See the * COPYRIGHT file at the base of the distribution. */ #include "defs.h" /* * Create missing directory path components, including the last path * element if specified. Intermediate directory path components are * allowed to exist and may contain softlinks. */ void mkdirpath(const char *path, int lastcomp) { const char *stop; const char *next; char *sub; struct stat st; stop = path; while (*stop == '/') ++stop; while (*stop) { if ((next = strchr(stop, '/')) == NULL) stop += strlen(stop); else stop = next; next = stop; while (*next == '/') ++next; if (lastcomp == 0 && *next == 0) break; sub = malloc(stop - path + 1); bcopy(path, sub, stop - path); sub[stop - path] = 0; if (stat(sub, &st) < 0) { if (errno != ENOENT) break; if (mkdir(sub, 0755) < 0) { if (errno != EEXIST) break; } } free(sub); stop = next; } }