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 symbolic = 0;
     19     int ret;
     20     if(argc < 2 || strcmp(argv[1], "--help") == 0) {
     21         return usage();
     22     }
     23 
     24     int recursive = (strcmp(argv[1], "-p") == 0 ||
     25                      strcmp(argv[1], "--parents") == 0) ? 1 : 0;
     26 
     27     if(recursive && argc < 3) {
     28         // -p specified without a path
     29         return usage();
     30     }
     31 
     32     if(recursive) {
     33         argc--;
     34         argv++;
     35     }
     36 
     37     char currpath[PATH_MAX], *pathpiece;
     38     struct stat st;
     39 
     40     while(argc > 1) {
     41         argc--;
     42         argv++;
     43         if(recursive) {
     44             // reset path
     45             strcpy(currpath, "");
     46             // create the pieces of the path along the way
     47             pathpiece = strtok(argv[0], "/");
     48             if(argv[0][0] == '/') {
     49                 // prepend / if needed
     50                 strcat(currpath, "/");
     51             }
     52             while(pathpiece != NULL) {
     53                 if(strlen(currpath) + strlen(pathpiece) + 2/*NUL and slash*/ > PATH_MAX) {
     54                     fprintf(stderr, "Invalid path specified: too long\n");
     55                     return 1;
     56                 }
     57                 strcat(currpath, pathpiece);
     58                 strcat(currpath, "/");
     59                 if(stat(currpath, &st) != 0) {
     60                     ret = mkdir(currpath, 0777);
     61                     if(ret < 0) {
     62                         fprintf(stderr, "mkdir failed for %s, %s\n", currpath, strerror(errno));
     63                         return ret;
     64                     }
     65                 }
     66                 pathpiece = strtok(NULL, "/");
     67             }
     68         } else {
     69             ret = mkdir(argv[0], 0777);
     70             if(ret < 0) {
     71                 fprintf(stderr, "mkdir failed for %s, %s\n", argv[0], strerror(errno));
     72                 return ret;
     73             }
     74         }
     75     }
     76 
     77     return 0;
     78 }
     79