core.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #define _XOPEN_SOURCE 500
  2. #include <ftw.h>
  3. #include "core.h"
  4. int mkdir_p(const char *path, mode_t mode)
  5. {
  6. /* Adapted from http://stackoverflow.com/a/2336245/119527 */
  7. const size_t len = strlen(path);
  8. char _path[PATH_MAX];
  9. char *p;
  10. errno = 0;
  11. /* Copy string so its mutable */
  12. if (len > sizeof(_path)-1) {
  13. errno = ENAMETOOLONG;
  14. return -1;
  15. }
  16. strcpy(_path, path);
  17. /* Iterate the string */
  18. for (p = _path + 1; *p; p++) {
  19. if (*p == '/') {
  20. /* Temporarily truncate */
  21. *p = '\0';
  22. if (mkdir(_path, mode) != 0) {
  23. if (errno != EEXIST)
  24. return -1;
  25. }
  26. *p = '/';
  27. }
  28. }
  29. if (mkdir(_path, mode) != 0) {
  30. if (errno != EEXIST)
  31. return -1;
  32. }
  33. return 0;
  34. }
  35. int
  36. unlink_cb(
  37. const char *fpath, const struct stat *sb, int typeflag,
  38. struct FTW *ftwbuf)
  39. {
  40. TRACE ("Removing %s\n", fpath);
  41. int rv = remove(fpath);
  42. if (rv)
  43. perror(fpath);
  44. return rv;
  45. }
  46. int rm_r(const char *path)
  47. { return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS); }
  48. /* Inline extern functions. */
  49. int utf8_encode(const uint32_t utf, unsigned char *out);