/* ISO C */ #include #include #include #include /* SuSv3 */ #include #include #include /* */ int mkdir_recursive(const char *pathname, mode_t mode) { const char *p=pathname; char d[_POSIX_PATH_MAX]; unsigned start, end; int res, last; res=0; for(start=0,last=0;p[start];start=end) { for(end=start;p[end]=='/';end++) ; if(!p[end]) break; for(;p[end] && p[end]!='/';end++) ; /* check if this is the last element, even with trailing / */ last=!p[strspn(p+end, "/")+end]; /* add this element to our buffer. */ memcpy(d+start, p+start, end-start); d[end]=0; /* fprintf(stderr, "DIR=\"%s\" start=%d end=%d ex='%.*s' last=%d\n", d, start, end, (int)(end-start), p+start, last); */ res=mkdir(d, mode); if(res) { if(!last && errno==EEXIST) { res=0; continue; /* ignore the existing directory. */ } /* fprintf(stderr, "Error:%s:%s:%s\n", pathname, d, strerror(errno)); */ return res; } } return res; }