logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

lib_mkdir.c (1185B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include "./lib_mkdir.h"
  6. #include <errno.h>
  7. #include <limits.h> // PATH_MAX
  8. #include <stdio.h> // fprintf
  9. #include <string.h> // strlen, strerror
  10. #include <sys/stat.h> // mkdir
  11. int
  12. mkdir_parents(char *path, mode_t mode)
  13. {
  14. for(int i = strlen(path) - 1; i >= 0; i--)
  15. {
  16. if(path[i] != '/') break;
  17. path[i] = 0;
  18. }
  19. char parent[PATH_MAX] = "";
  20. strncpy(parent, path, PATH_MAX);
  21. for(int i = strlen(parent) - 1; i >= 0; i--)
  22. {
  23. if(parent[i] == '/') break;
  24. parent[i] = 0;
  25. }
  26. if(path[0] == 0) return 0;
  27. mode_t parent_mode = (S_IWUSR | S_IXUSR | ~mkdir_parents_filemask) & 0777;
  28. if(mkdir_parents(parent, parent_mode) < 0) return -1;
  29. if(mkdir(path, mode) < 0)
  30. {
  31. if(errno == EEXIST)
  32. {
  33. errno = 0;
  34. return 0;
  35. }
  36. fprintf(stderr, "%s: error: Failed making directory '%s': %s\n", argv0, path, strerror(errno));
  37. errno = 0;
  38. return -1;
  39. }
  40. if(mkdir_parents_verbose) fprintf(stderr, "%s: Made directory: %s\n", argv0, path);
  41. return 0;
  42. }