path.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #pragma once
  15. #include <fstream>
  16. #include <string>
  17. #include <vector>
  18. #ifdef _MSC_VER
  19. #define PATH_SEP "\\"
  20. #else
  21. #define PATH_SEP "/"
  22. #endif
  23. namespace ultra_infer {
  24. inline std::string PathJoin(const std::vector<std::string> &paths,
  25. const std::string &sep = PATH_SEP) {
  26. if (paths.size() == 1) {
  27. return paths[0];
  28. }
  29. std::string filepath = "";
  30. for (const auto &path : paths) {
  31. if (filepath == "") {
  32. filepath += path;
  33. continue;
  34. }
  35. if (path[0] == sep[0] || filepath.back() == sep[0]) {
  36. filepath += path;
  37. } else {
  38. filepath += sep + path;
  39. }
  40. }
  41. return filepath;
  42. }
  43. inline std::string PathJoin(const std::string &folder,
  44. const std::string &filename,
  45. const std::string &sep = PATH_SEP) {
  46. return PathJoin(std::vector<std::string>{folder, filename}, sep);
  47. }
  48. inline std::string GetDirFromPath(const std::string &path) {
  49. auto pos = path.find_last_of(PATH_SEP);
  50. if (pos == std::string::npos) {
  51. return "";
  52. }
  53. // The root path in UNIX systems
  54. if (pos == 0) {
  55. return "/";
  56. }
  57. return path.substr(0, pos);
  58. }
  59. inline bool CheckFileExists(const std::string &path) {
  60. std::fstream fin(path, std::ios::in);
  61. if (!fin) {
  62. return false;
  63. }
  64. return true;
  65. }
  66. } // namespace ultra_infer