hpath.cpp 2.5 KB

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