9#include <nlohmann/json.hpp>
15#define FMT_HEADER_ONLY
16#include <fmt/format.h>
17#include <fmt/ostream.h>
21 namespace fs = std::filesystem;
31 std::ifstream f(file.c_str());
43 std::vector<uint8_t>
slurp(
const std::string& file,
bool optional =
false)
45 std::ifstream f(file, std::ios::binary | std::ios::ate);
55 std::cerr <<
"Could not open file " << file << std::endl;
60 auto size = f.tellg();
61 f.seekg(0, std::ios::beg);
63 std::vector<uint8_t> data(size);
64 f.read((
char*)data.data(), size);
68 std::cerr <<
"Could not read file " << file << std::endl;
82 std::string
slurp_string(
const std::string& file,
bool optional =
false)
84 auto v =
slurp(file, optional);
85 return {v.begin(), v.end()};
90 if (!fs::exists(file))
106 nlohmann::json
slurp_json(
const std::string& file,
bool optional =
false)
108 auto v =
slurp(file, optional);
110 return nlohmann::json();
112 return nlohmann::json::parse(v.begin(), v.end());
121 void dump(
const std::vector<uint8_t>& data,
const std::string& file)
124 ofstream f(file, ios::binary | ios::trunc);
125 f.write((
char*)data.data(), data.size());
127 throw logic_error(
"Failed to write to file: " + file);
136 void dump(
const std::string& data,
const std::string& file)
138 return dump(std::vector<uint8_t>(data.begin(), data.end()), file);
141 void rename(
const fs::path& src,
const fs::path& dst)
144 fs::rename(src, dst, ec);
147 throw std::logic_error(fmt::format(
148 "Could not rename file {} to {}: {}",
std::vector< uint8_t > slurp(const std::string &file, bool optional=false)
Tries to read a file as byte vector.
Definition files.h:43
void dump(const std::vector< uint8_t > &data, const std::string &file)
Writes the content of a vector to a file.
Definition files.h:121
void rename(const fs::path &src, const fs::path &dst)
Definition files.h:141
std::string slurp_string(const std::string &file, bool optional=false)
Tries to read a file as string.
Definition files.h:82
nlohmann::json slurp_json(const std::string &file, bool optional=false)
Tries to read a file as JSON.
Definition files.h:106
bool exists(const std::string &file)
Checks if a path exists.
Definition files.h:29
std::optional< std::string > try_slurp_string(const std::string &file)
Definition files.h:88