1
0

mkdir.c 1.0 KB

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