From 06f9faeb3235b5bc030903a8493bf2de58f709df Mon Sep 17 00:00:00 2001 From: heck Date: Sat, 25 Sep 2021 16:55:13 +0200 Subject: [PATCH] std_utils.hh - add path_dirname() and path_get_abs(); --- src/std_utils.cc | 40 ++++++++++++++++++++++++++++++++++++++++ src/std_utils.hh | 5 +++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/std_utils.cc b/src/std_utils.cc index 51aa7cf..5102fdd 100644 --- a/src/std_utils.cc +++ b/src/std_utils.cc @@ -15,6 +15,7 @@ #ifndef WIN32 #include #include + #include #endif using namespace std; @@ -99,6 +100,44 @@ namespace pEp { throw_with_nested(e); } } + + std::string path_dirname(std::string const& f) + { + if (f.empty()) + return f; + if (f == "/") + return ""; + + auto len = f.size(); + // if the last character is / or \ ignore it + if (f[len - 1] == '/' || f[len - 1] == '\\') + --len; + while (len > 0) { + --len; + if (f[len] == '/' || f[len] == '\\') + break; + } + + if (f[len] == '/' || f[len] == '\\') + ++len; + return std::string(f.c_str(), len); + } + + std::string path_get_abs(const std::string& path) + { + std::string ret{ path }; + if (path[0] != '/') { + char cwd[2048]; + char const* res = getcwd(cwd, sizeof(cwd)); + if (res == nullptr) { + throw std::runtime_error( + "failed to get current working directory: " + std::string(strerror(errno))); + } + ret = std::string(cwd) + "/" + path; + } + return ret; + } + #endif ofstream file_create(const string &filename) @@ -153,6 +192,7 @@ namespace pEp { } } + void dir_create(const string &dirname, const mode_t mode) { if (mkdir(dirname.c_str(), mode) != 0) { diff --git a/src/std_utils.hh b/src/std_utils.hh index 8f54e45..301f063 100644 --- a/src/std_utils.hh +++ b/src/std_utils.hh @@ -29,12 +29,13 @@ namespace pEp { // path (file & dir) bool path_exists(const std::string &filename); void path_delete(const std::string &filename); - bool path_is_dir(const std::string &path); #ifndef WIN32 + bool path_is_dir(const std::string &path); void path_delete_all(const std::string &path); + std::string path_dirname(std::string const& f); + std::string path_get_abs(const std::string& path); #endif - void path_ensure_not_existing(const std::string &path); // file