Header file.h
This header provides helper functions to read/write data from/to files easily.
Examples
The following code snippet reads a file and computes SHA-1 hash of the contents:
1#include <clu/file.h>
2#include <clu/assertion.h>
3
4int main()
5{
6 std::vector<int> data{ 1, 2, 3, 4 };
7 clu::write_all_bytes("data.bin", data);
8 const auto read = clu::read_all_bytes<int>("data.bin"); // read as vector of ints
9 const auto bytes = clu::read_all_bytes("data.bin"); // default behavior is to read as vector of bytes
10 CLU_ASSERT(read == data);
11
12 clu::write_all_text("data.txt", "Hello, world!");
13 const std::string text = clu::read_all_text("data.txt");
14 CLU_ASSERT(text == "Hello, world!");
15}
-
template<trivially_copyable T = std::byte, allocator_for<T> Alloc = std::allocator<T>>
std::vector<T, Alloc> clu::read_all_bytes(const std::filesystem::path &path, const Alloc &alloc = Alloc{}) Read contents of a binary file into a
std::vector
.- Template Parameters
T – Value type of the result vector. It must be trivially copyable.
Alloc – Allocator type used by the vector.
- Parameters
path – The path to the file to read from.
alloc – The allocator for allocating the vector.
-
std::string clu::read_all_text(const std::filesystem::path &path)
Reads contents of a text file into a
std::string
.- Parameters
path – The path to the file to read from.
-
void clu::write_all_bytes(const std::filesystem::path &path, const_buffer bytes)
Writes bytes in a given buffer into a file. The file will be overwritten.
- Parameters
path – The path to the file to write into.
bytes – The byte buffer.