mkdir.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. char *e;
  12. uint32_t mode = 0777L;
  13. void
  14. usage(void)
  15. {
  16. fprint(2, "usage: mkdir [-p] [-m mode] dir...\n");
  17. exits("usage");
  18. }
  19. int
  20. makedir(char *s)
  21. {
  22. int f;
  23. if(access(s, AEXIST) == 0){
  24. fprint(2, "mkdir: %s already exists\n", s);
  25. e = "error";
  26. return -1;
  27. }
  28. f = create(s, OREAD, DMDIR | mode);
  29. if(f < 0){
  30. fprint(2, "mkdir: can't create %s: %r\n", s);
  31. e = "error";
  32. return -1;
  33. }
  34. close(f);
  35. return 0;
  36. }
  37. void
  38. mkdirp(char *s)
  39. {
  40. char *p;
  41. for(p=strchr(s+1, '/'); p; p=strchr(p+1, '/')){
  42. *p = 0;
  43. if(access(s, AEXIST) != 0 && makedir(s) < 0)
  44. return;
  45. *p = '/';
  46. }
  47. if(access(s, AEXIST) != 0)
  48. makedir(s);
  49. }
  50. void
  51. main(int argc, char *argv[])
  52. {
  53. int i, pflag;
  54. char *m;
  55. pflag = 0;
  56. ARGBEGIN{
  57. default:
  58. usage();
  59. case 'm':
  60. m = ARGF();
  61. if(m == nil)
  62. usage();
  63. mode = strtoul(m, &m, 8);
  64. if(mode > 0777)
  65. usage();
  66. break;
  67. case 'p':
  68. pflag = 1;
  69. break;
  70. }ARGEND
  71. for(i=0; i<argc; i++){
  72. if(pflag)
  73. mkdirp(argv[i]);
  74. else
  75. makedir(argv[i]);
  76. }
  77. exits(e);
  78. }