Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 // name=mkdirp ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
0002 // https://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
0003 
0004 #include <cstring>
0005 #include <cstdlib>
0006 #include <cstdio>
0007 #include <sys/stat.h>
0008 #include <errno.h>
0009 
0010 /**
0011 //                        0700      040        010       04        01 
0012 
0013 In [13]: print(oct(0o700 | 0o40 | 0o10 | 0o4 | 0o01))                                                                                                                                                     
0014 0o755
0015 
0016 **/
0017 
0018 int mkdirp(const char* path, int mode_ = 0  );
0019 
0020 
0021 int mkdirp(const char* path_, int mode_ ) 
0022 {
0023     mode_t default_mode = S_IRWXU | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH ; 
0024     mode_t mode = mode_ == 0 ? default_mode : mode_ ;  
0025 
0026     char* path = strdup(path_);
0027     char* p = path ;  
0028     int rc = 0 ; 
0029 
0030     while (*p != '\0' && rc == 0) 
0031     {
0032         p++;                                 // advance past leading character, probably slash, and subsequent slashes the next line gets to  
0033         while(*p != '\0' && *p != '/') p++;  // advance p until subsequent slash 
0034         char v = *p;                         // store the slash      
0035         *p = '\0' ;                          // replace slash with string terminator
0036         printf("%s\n", path ); 
0037         rc = mkdir(path, mode) == -1 && errno != EEXIST ? 1 : 0 ;  // set rc non-zero for mkdir errors other than exists already  
0038         *p = v;                              // put back the slash 
0039     }
0040     free(path); 
0041     return rc ;
0042 }
0043 
0044 int main(int argc, char** argv)
0045 {
0046     const char* path = "/tmp/red/green/blue" ; 
0047     int mode = 0777 ; 
0048     int rc = mkdirp(path, mode); 
0049     return rc ; 
0050 }
0051 
0052 
0053