Skip to content
Snippets Groups Projects
Commit 9bf6a539 authored by Adrien Béraud's avatar Adrien Béraud Committed by gerrit2
Browse files

fileutils: add isPathRelative(), default root to loadFile()


Make it easier to use relative paths across the daemon.

Change-Id: I53fe0b384d48d0dde9ad11a9e0c03714c7ad3766
Reviewed-by: default avatarGuillaume Roguez <guillaume.roguez@savoirfairelinux.com>
parent b0457db5
Branches
Tags
No related merge requests found
......@@ -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);
......
......@@ -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 {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment