Util.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "Util.hpp"
  2. #include <dirent.h>
  3. #include <sys/unistd.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <cpp3ds/System/FileSystem.hpp>
  8. namespace FreeShop
  9. {
  10. bool pathExists(const char* path, bool escape)
  11. {
  12. struct stat buffer;
  13. if (escape)
  14. return stat(cpp3ds::FileSystem::getFilePath(path).c_str(), &buffer) == 0;
  15. else
  16. return stat(path, &buffer) == 0;
  17. }
  18. void makeDirectory(const char *dir, mode_t mode)
  19. {
  20. char tmp[256];
  21. char *p = NULL;
  22. size_t len;
  23. snprintf(tmp, sizeof(tmp),"%s",dir);
  24. len = strlen(tmp);
  25. if(tmp[len - 1] == '/')
  26. tmp[len - 1] = 0;
  27. for(p = tmp + 1; *p; p++)
  28. if(*p == '/') {
  29. *p = 0;
  30. mkdir(tmp, mode);
  31. *p = '/';
  32. }
  33. mkdir(tmp, mode);
  34. }
  35. int removeDirectory(const char *path, bool onlyIfEmpty)
  36. {
  37. DIR *d = opendir(path);
  38. size_t path_len = strlen(path);
  39. int r = -1;
  40. if (d) {
  41. struct dirent *p;
  42. r = 0;
  43. while (!r && (p = readdir(d))) {
  44. int r2 = -1;
  45. char *buf;
  46. size_t len;
  47. /* Skip the names "." and ".." as we don't want to recurse on them. */
  48. if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
  49. continue;
  50. len = path_len + strlen(p->d_name) + 2;
  51. buf = (char*) malloc(len);
  52. if (buf) {
  53. struct stat sb;
  54. snprintf(buf, len, "%s/%s", path, p->d_name);
  55. if (!stat(buf, &sb)) {
  56. if (S_ISDIR(sb.st_mode))
  57. r2 = removeDirectory(buf, onlyIfEmpty);
  58. else if (!onlyIfEmpty)
  59. r2 = unlink(buf);
  60. }
  61. free(buf);
  62. }
  63. r = r2;
  64. }
  65. closedir(d);
  66. }
  67. if (!r)
  68. r = rmdir(path);
  69. return r;
  70. }
  71. } // namespace FreeShop