The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <unistd.h> |
| 3 | #include <string.h> |
| 4 | #include <errno.h> |
Anthony Newnam | b55de67 | 2010-07-06 18:18:35 -0500 | [diff] [blame] | 5 | #include <sys/limits.h> |
| 6 | #include <sys/stat.h> |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 7 | |
| 8 | static int usage() |
| 9 | { |
Anthony Newnam | b55de67 | 2010-07-06 18:18:35 -0500 | [diff] [blame] | 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"); |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 13 | return -1; |
| 14 | } |
| 15 | |
| 16 | int mkdir_main(int argc, char *argv[]) |
| 17 | { |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 18 | int ret; |
Anthony Newnam | b55de67 | 2010-07-06 18:18:35 -0500 | [diff] [blame] | 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; |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 38 | |
| 39 | while(argc > 1) { |
| 40 | argc--; |
| 41 | argv++; |
Anthony Newnam | b55de67 | 2010-07-06 18:18:35 -0500 | [diff] [blame] | 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 | } |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 73 | } |
| 74 | } |
| 75 | |
| 76 | return 0; |
| 77 | } |