hpath.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "hpath.h"
  2. #include "hplatform.h"
  3. bool HPath::exists(const char* path) {
  4. return access(path, 0) == 0;
  5. }
  6. bool HPath::isdir(const char* path) {
  7. if (access(path, 0) != 0) return false;
  8. struct stat st;
  9. memset(&st, 0, sizeof(st));
  10. stat(path, &st);
  11. return S_ISDIR(st.st_mode);
  12. }
  13. bool HPath::isfile(const char* path) {
  14. if (access(path, 0) != 0) return false;
  15. struct stat st;
  16. memset(&st, 0, sizeof(st));
  17. stat(path, &st);
  18. return S_ISREG(st.st_mode);
  19. }
  20. std::string HPath::basename(const std::string& filepath) {
  21. std::string::size_type pos1 = filepath.find_last_not_of("/\\");
  22. if (pos1 == std::string::npos) {
  23. return "/";
  24. }
  25. std::string::size_type pos2 = filepath.find_last_of("/\\", pos1);
  26. if (pos2 == std::string::npos) {
  27. pos2 = 0;
  28. } else {
  29. pos2++;
  30. }
  31. return filepath.substr(pos2, pos1-pos2+1);
  32. }
  33. std::string HPath::dirname(const std::string& filepath) {
  34. std::string::size_type pos1 = filepath.find_last_not_of("/\\");
  35. if (pos1 == std::string::npos) {
  36. return "/";
  37. }
  38. std::string::size_type pos2 = filepath.find_last_of("/\\", pos1);
  39. if (pos2 == std::string::npos) {
  40. return ".";
  41. } else if (pos2 == 0) {
  42. pos2 = 1;
  43. }
  44. return filepath.substr(0, pos2);
  45. }
  46. std::string HPath::filename(const std::string& filepath) {
  47. std::string::size_type pos1 = filepath.find_last_of("/\\");
  48. if (pos1 == std::string::npos) {
  49. pos1 = 0;
  50. } else {
  51. pos1++;
  52. }
  53. std::string file = filepath.substr(pos1, -1);
  54. std::string::size_type pos2 = file.find_last_of(".");
  55. if (pos2 == std::string::npos) {
  56. return file;
  57. }
  58. return file.substr(0, pos2);
  59. }
  60. std::string HPath::suffixname(const std::string& filepath) {
  61. std::string::size_type pos1 = filepath.find_last_of("/\\");
  62. if (pos1 == std::string::npos) {
  63. pos1 = 0;
  64. } else {
  65. pos1++;
  66. }
  67. std::string file = filepath.substr(pos1, -1);
  68. std::string::size_type pos2 = file.find_last_of(".");
  69. if (pos2 == std::string::npos) {
  70. return "";
  71. }
  72. return file.substr(pos2+1, -1);
  73. }
  74. std::string HPath::join(const std::string& dir, const std::string& filename) {
  75. char separator = '/';
  76. #ifdef OS_WIN
  77. if (dir.find_first_of("\\") != std::string::npos) {
  78. separator = '\\';
  79. }
  80. #endif
  81. std::string filepath(dir);
  82. if (dir[dir.length()-1] != separator) {
  83. filepath += separator;
  84. }
  85. filepath += filename;
  86. return filepath;
  87. }