21 namespace fs = std::filesystem;
29 static bool exists(
const std::string& file)
31 std::ifstream f(file.c_str());
43 static std::vector<uint8_t> slurp(
44 const std::string& file,
bool optional =
false)
46 std::ifstream f(file, std::ios::binary | std::ios::ate);
56 std::cerr <<
"Could not open file " << file << std::endl;
61 auto size = f.tellg();
62 f.seekg(0, std::ios::beg);
64 std::vector<uint8_t> data(size);
65 f.read((
char*)data.data(), size);
69 std::cerr <<
"Could not read file " << file << std::endl;
83 static std::string slurp_string(
84 const std::string& file,
bool optional =
false)
86 auto v = slurp(file, optional);
87 return {v.begin(), v.end()};
90 static std::optional<std::string> try_slurp_string(
const std::string& file)
92 if (!fs::exists(file))
96 return files::slurp_string(file);
108 static nlohmann::json slurp_json(
109 const std::string& file,
bool optional =
false)
111 auto v = slurp(file, optional);
113 return nlohmann::json();
115 return nlohmann::json::parse(v.begin(), v.end());
124 static void dump(
const std::vector<uint8_t>& data,
const std::string& file)
127 ofstream f(file, ios::binary | ios::trunc);
128 f.write((
char*)data.data(), data.size());
130 throw logic_error(
"Failed to write to file: " + file);
139 static void dump(
const std::string& data,
const std::string& file)
141 return dump(std::vector<uint8_t>(data.begin(), data.end()), file);
144 static void rename(
const fs::path& src,
const fs::path& dst)
147 fs::rename(src, dst, ec);
150 throw std::logic_error(fmt::format(
151 "Could not rename file {} to {}: {}",
158 static void create_directory(
const fs::path& dir)
161 fs::create_directory(dir, ec);
162 if (ec && ec != std::errc::file_exists)
164 throw std::logic_error(fmt::format(
165 "Could not create directory {}: {}", dir.string(), ec.message()));