diff --git a/src/fileutils.cpp b/src/fileutils.cpp index 5148f7c708d470dccd3a1a84e30a8c7dc0e57069..bd040d5a7020112f96a01fa540080143dc21cb44 100644 --- a/src/fileutils.cpp +++ b/src/fileutils.cpp @@ -290,11 +290,21 @@ writeTime(const std::string& path) #endif } +bool isPathRelative(const std::string& path) +{ +#ifndef _WIN32 + return not path.empty() and not (path[0] == '/'); +#else + return not path.empty() and path.find(":") == std::string::npos; +#endif +} + std::vector<uint8_t> -loadFile(const std::string& path) +loadFile(const std::string& path, const std::string& default_dir) { + bool isRelative {not default_dir.empty() and isPathRelative(path)}; std::vector<uint8_t> buffer; - std::ifstream file(path, std::ios::binary); + std::ifstream file(isRelative ? default_dir + DIR_SEPARATOR_STR + path : path, std::ios::binary); if (!file) throw std::runtime_error("Can't read file: "+path); file.seekg(0, std::ios::end); diff --git a/src/fileutils.h b/src/fileutils.h index 12f7a5d57d6b713a12c614e45c19356c5183dcbe..5d3d3c64f353d7e1fd43c1a2c908e90799d082e1 100644 --- a/src/fileutils.h +++ b/src/fileutils.h @@ -26,11 +26,11 @@ #include <chrono> #include <cstdio> -#ifndef RING_UWP -#define PROTECTED_GETENV(str) ({char *envvar_ = getenv((str)); \ - envvar_ ? envvar_ : "";}) -#else -#define PROTECTED_GETENV(str) ({char *envvar_ = "" }) +#ifndef RING_UWP +#define PROTECTED_GETENV(str) ({char *envvar_ = getenv((str)); \ + envvar_ ? envvar_ : "";}) +#else +#define PROTECTED_GETENV(str) ({char *envvar_ = "" }) #endif #define XDG_DATA_HOME (PROTECTED_GETENV("XDG_DATA_HOME")) @@ -70,6 +70,8 @@ namespace ring { namespace fileutils { bool recursive_mkdir(const std::string& path, mode_t mode=0755); + bool isPathRelative(const std::string& path); + bool isFile(const std::string& path); bool isDirectory(const std::string& path); @@ -84,7 +86,11 @@ namespace ring { namespace fileutils { */ std::vector<std::string> readDirectory(const std::string &dir); - std::vector<uint8_t> loadFile(const std::string& path); + /** + * Read the full content of a file at path. + * If path is relative, it is appended to default_dir. + */ + std::vector<uint8_t> loadFile(const std::string& path, const std::string& default_dir = {}); void saveFile(const std::string& path, const std::vector<uint8_t>& data, mode_t mode=0644); struct FileHandle {