mkdir.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* vim:tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013-2014 K. Lange
  5. *
  6. * mkdir
  7. *
  8. * Create a directory.
  9. */
  10. #include <stdio.h>
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <getopt.h>
  15. #include <errno.h>
  16. #include <sys/stat.h>
  17. #include <sys/types.h>
  18. int makedir(const char * dir, int mask, int parents) {
  19. if (!parents) return mkdir(dir,mask);
  20. char * tmp = strdup(dir);
  21. char * c = tmp;
  22. while ((c = strchr(c+1,'/'))) {
  23. *c = '\0';
  24. if (mkdir(tmp,mask) < 0) {
  25. if (errno == EEXIST) {
  26. *c = '/';
  27. continue;
  28. } else {
  29. return -1;
  30. }
  31. }
  32. *c = '/';
  33. continue;
  34. }
  35. return mkdir(tmp, mask);
  36. }
  37. int main(int argc, char ** argv) {
  38. int retval = 0;
  39. int parents = 0;
  40. int opt;
  41. while ((opt = getopt(argc, argv, "m:p")) != -1) {
  42. switch (opt) {
  43. case 'm':
  44. fprintf(stderr, "%s: -m unsupported\n", argv[0]);
  45. return 1;
  46. case 'p':
  47. parents = 1;
  48. break;
  49. }
  50. }
  51. if (optind == argc) {
  52. fprintf(stderr, "%s: expected argument\n", argv[0]);
  53. return 1;
  54. }
  55. for (int i = optind; i < argc; ++i) {
  56. if (makedir(argv[i], 0777, parents) < 0) {
  57. if (parents && errno == EEXIST) continue;
  58. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[i], strerror(errno));
  59. retval = 1;
  60. }
  61. }
  62. return retval;
  63. }