From 9bf6a539dda09aa1b007534d516f88ee4d17edfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com> Date: Wed, 25 Jan 2017 17:03:49 -0500 Subject: [PATCH] fileutils: add isPathRelative(), default root to loadFile() Make it easier to use relative paths across the daemon. Change-Id: I53fe0b384d48d0dde9ad11a9e0c03714c7ad3766 Reviewed-by: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com> --- src/fileutils.cpp | 14 ++++++++++++-- src/fileutils.h | 18 ++++++++++++------ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/fileutils.cpp b/src/fileutils.cpp index 5148f7c708..bd040d5a70 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 12f7a5d57d..5d3d3c64f3 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 { -- GitLab