make_dir_path.c 813 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Make a path of subdirectories, tolerating EEXIST at every step.
  3. */
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include "putty.h"
  10. char *make_dir_path(const char *path, mode_t mode)
  11. {
  12. int pos = 0;
  13. char *prefix;
  14. while (1) {
  15. pos += strcspn(path + pos, "/");
  16. if (pos > 0) {
  17. prefix = dupprintf("%.*s", pos, path);
  18. if (mkdir(prefix, mode) < 0 && errno != EEXIST) {
  19. char *ret = dupprintf("%s: mkdir: %s",
  20. prefix, strerror(errno));
  21. sfree(prefix);
  22. return ret;
  23. }
  24. sfree(prefix);
  25. }
  26. if (!path[pos])
  27. return NULL;
  28. pos += strspn(path + pos, "/");
  29. }
  30. }