Home | History | Annotate | Download | only in toolbox
      1 #include <stdio.h>
      2 #include <unistd.h>
      3 #include <string.h>
      4 #include <errno.h>
      5 #include <sys/limits.h>
      6 #include <sys/stat.h>
      7 
      8 static int usage()
      9 {
     10     fprintf(stderr,"mkdir [OPTION] <target>\n");
     11     fprintf(stderr,"    --help           display usage and exit\n");
     12     fprintf(stderr,"    -p, --parents    create parent directories as needed\n");
     13     return -1;
     14 }
     15 
     16 int mkdir_main(int argc, char *argv[])
     17 {
     18     int ret;
     19     if(argc < 2 || strcmp(argv[1], "--help") == 0) {
     20         return usage();
     21     }
     22 
     23     int recursive = (strcmp(argv[1], "-p") == 0 ||
     24                      strcmp(argv[1], "--parents") == 0) ? 1 : 0;
     25 
     26     if(recursive && argc < 3) {
     27         // -p specified without a path
     28         return usage();
     29     }
     30 
     31     if(recursive) {
     32         argc--;
     33         argv++;
     34     }
     35 
     36     char currpath[PATH_MAX], *pathpiece;
     37     struct stat st;
     38 
     39     while(argc > 1) {
     40         argc--;
     41         argv++;
     42         if(recursive) {
     43             // reset path
     44             strcpy(currpath, "");
     45             // create the pieces of the path along the way
     46             pathpiece = strtok(argv[0], "/");
     47             if(argv[0][0] == '/') {
     48                 // prepend / if needed
     49                 strcat(currpath, "/");
     50             }
     51             while(pathpiece != NULL) {
     52                 if(strlen(currpath) + strlen(pathpiece) + 2/*NUL and slash*/ > PATH_MAX) {
     53                     fprintf(stderr, "Invalid path specified: too long\n");
     54                     return 1;
     55                 }
     56                 strcat(currpath, pathpiece);
     57                 strcat(currpath, "/");
     58                 if(stat(currpath, &st) != 0) {
     59                     ret = mkdir(currpath, 0777);
     60                     if(ret < 0) {
     61                         fprintf(stderr, "mkdir failed for %s, %s\n", currpath, strerror(errno));
     62                         return ret;
     63                     }
     64                 }
     65                 pathpiece = strtok(NULL, "/");
     66             }
     67         } else {
     68             ret = mkdir(argv[0], 0777);
     69             if(ret < 0) {
     70                 fprintf(stderr, "mkdir failed for %s, %s\n", argv[0], strerror(errno));
     71                 return ret;
     72             }
     73         }
     74     }
     75 
     76     return 0;
     77 }
     78