Browse Source

std_utils.hh - add path_dirname() and path_get_abs();

LIB-18
heck 4 years ago
parent
commit
06f9faeb32
  1. 40
      src/std_utils.cc
  2. 5
      src/std_utils.hh

40
src/std_utils.cc

@ -15,6 +15,7 @@
#ifndef WIN32
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#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) {

5
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

Loading…
Cancel
Save