blob: 398d350f7298d02a23a92c6bb02e92eeab37c137 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001#include <stdio.h>
2#include <unistd.h>
3#include <string.h>
4#include <errno.h>
Anthony Newnamb55de672010-07-06 18:18:35 -05005#include <sys/limits.h>
6#include <sys/stat.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08007
8static int usage()
9{
Anthony Newnamb55de672010-07-06 18:18:35 -050010 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 Projectdd7bc332009-03-03 19:32:55 -080013 return -1;
14}
15
16int mkdir_main(int argc, char *argv[])
17{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080018 int ret;
Anthony Newnamb55de672010-07-06 18:18:35 -050019 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 Projectdd7bc332009-03-03 19:32:55 -080038
39 while(argc > 1) {
40 argc--;
41 argv++;
Anthony Newnamb55de672010-07-06 18:18:35 -050042 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 Projectdd7bc332009-03-03 19:32:55 -080073 }
74 }
75
76 return 0;
77}