mkdir.c (1026B)
1 #include <u.h> 2 #include <libc.h> 3 4 char *e; 5 ulong mode = 0777L; 6 7 void 8 usage(void) 9 { 10 fprint(2, "usage: mkdir [-p] [-m mode] dir...\n"); 11 exits("usage"); 12 } 13 14 int 15 makedir(char *s) 16 { 17 int f; 18 19 if(access(s, AEXIST) == 0){ 20 fprint(2, "mkdir: %s already exists\n", s); 21 e = "error"; 22 return -1; 23 } 24 f = create(s, OREAD, DMDIR | mode); 25 if(f < 0){ 26 fprint(2, "mkdir: can't create %s: %r\n", s); 27 e = "error"; 28 return -1; 29 } 30 close(f); 31 return 0; 32 } 33 34 void 35 mkdirp(char *s) 36 { 37 char *p; 38 39 for(p=strchr(s+1, '/'); p; p=strchr(p+1, '/')){ 40 *p = 0; 41 if(access(s, AEXIST) != 0 && makedir(s) < 0) 42 return; 43 *p = '/'; 44 } 45 if(access(s, AEXIST) != 0) 46 makedir(s); 47 } 48 49 50 void 51 main(int argc, char *argv[]) 52 { 53 int i, pflag; 54 char *m; 55 56 pflag = 0; 57 ARGBEGIN{ 58 default: 59 usage(); 60 case 'm': 61 m = ARGF(); 62 if(m == nil) 63 usage(); 64 mode = strtoul(m, &m, 8); 65 if(mode > 0777) 66 usage(); 67 break; 68 case 'p': 69 pflag = 1; 70 break; 71 }ARGEND 72 73 for(i=0; i<argc; i++){ 74 if(pflag) 75 mkdirp(argv[i]); 76 else 77 makedir(argv[i]); 78 } 79 exits(e); 80 }