blob: 656970a7175a7cb401ed230eb9995e6c014075d0 [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{
18 int symbolic = 0;
19 int ret;
Anthony Newnamb55de672010-07-06 18:18:35 -050020 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039
40 while(argc > 1) {
41 argc--;
42 argv++;
Anthony Newnamb55de672010-07-06 18:18:35 -050043 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 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080074 }
75 }
76
77 return 0;
78}