xmkdirp.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Error-checking replacement for "mkdir -p".
  2. Copyright (C) 2018-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <support/support.h>
  16. #include <support/check.h>
  17. #include <support/xunistd.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <errno.h>
  21. /* Equivalent of "mkdir -p". Any failures cause FAIL_EXIT1 so no
  22. return code is needed. */
  23. void
  24. xmkdirp (const char *path, mode_t mode)
  25. {
  26. struct stat s;
  27. const char *slash_p;
  28. int rv;
  29. if (path[0] == 0)
  30. return;
  31. if (stat (path, &s) == 0)
  32. {
  33. if (S_ISDIR (s.st_mode))
  34. return;
  35. errno = EEXIST;
  36. FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
  37. }
  38. slash_p = strrchr (path, '/');
  39. if (slash_p != NULL)
  40. {
  41. while (slash_p > path && slash_p[-1] == '/')
  42. --slash_p;
  43. if (slash_p > path)
  44. {
  45. char *parent = xstrndup (path, slash_p - path);
  46. xmkdirp (parent, mode);
  47. free (parent);
  48. }
  49. }
  50. rv = mkdir (path, mode);
  51. if (rv != 0)
  52. FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
  53. return;
  54. }