8 namespace fs = std::filesystem;
15 [[nodiscard]]
static std::string
read(
const fs::path& filename) {
16 if (std::ifstream ifs{filename, std::ios::ate | std::ios::binary}) {
17 std::string buffer(ifs.tellg(),
'\000');
18 ifs.seekg(0, std::ios::beg);
19 ifs.read(buffer.data(), buffer.size());
23 throw Exception(
"No such file " + filename.string());
29 [[nodiscard]]
static std::vector<std::string>
readLines(
const fs::path& filename) {
30 if (std::ifstream ifs{filename, std::ios::binary}) {
31 std::vector<std::string> lines{};
33 while (std::getline(ifs, line)) {
34 lines.push_back(line);
39 throw Exception(
"No such file " + filename.string());
45 static void readChunks(
const fs::path& filename,
const std::size_t maxChunkSize,
const std::function<
void(std::vector<std::uint8_t>&&)>& callback) {
46 if (std::ifstream ifs{filename, std::ios::binary}) {
48 std::vector<std::uint8_t> chunk(maxChunkSize,
'\000');
49 ifs.read(
reinterpret_cast<char *
>(chunk.data()), chunk.size());
52 const auto bytes_read =
static_cast<std::size_t
>(ifs.gcount());
53 if (bytes_read < maxChunkSize)
54 chunk.resize(bytes_read);
57 callback(std::move(chunk));
61 throw Exception(
"No such file " + filename.string());
67 static void write(
const fs::path& filename,
const std::string& buffer) {
68 if (std::ofstream ofs{filename, std::ios::binary}) {
69 ofs.write(buffer.data(), buffer.size());
72 throw Exception(
"Failed to write file " + filename.string());
static void write(const fs::path &filename, const std::string &buffer)
Write buffer string to a new file.
static std::string read(const fs::path &filename)
Read entire file into an std::string.
static std::vector< std::string > readLines(const fs::path &filename)
Read entire file lines into std::vector<std::string>
static void readChunks(const fs::path &filename, const std::size_t maxChunkSize, const std::function< void(std::vector< std::uint8_t > &&)> &callback)
Read file chunk by chunk.