Skip to content

Instantly share code, notes, and snippets.

@kwsp
Last active September 9, 2024 17:05
Show Gist options
  • Save kwsp/5d15c81d97749536fe1785e499c7dc02 to your computer and use it in GitHub Desktop.
Save kwsp/5d15c81d97749536fe1785e499c7dc02 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <armadillo>
// T is the type of value stored in the binary file.
template <typename T>
auto load_bin(const fs::path &filename) -> arma::Mat<T> {
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
std::cerr << "Failed to open file\n";
return {};
}
const std::streamsize fsize = file.tellg();
file.seekg(0, std::ios::beg);
const auto n_values = fsize / sizeof(T);
const size_t cols = 1000;
const size_t rows = n_values / cols;
// Check if the file size matches our matrix size
if (rows * cols * sizeof(T) != fsize) {
std::cerr << "File size does not match the expected matrix dimensions\n";
return {};
}
arma::Mat<T> matrix(rows, cols);
// Read file
if (!file.read(
reinterpret_cast<char *>(matrix.data()), // NOLINT(*-reinterpret-cast)
fsize)) {
std::cerr << "Failed to read data into matrix\n";
return {};
}
return matrix;
}
/**
@brief write a span of data to a binary file.
@tparam T The type of the elements in the span. Must be trivially copyable.
@param filename The name of the file to write to.
@param data A span consisting of the data to be written. The span provides a
view into a sequence of objects of type `T`.
*/
template <typename T>
void to_bin(const fs::path &filename, std::span<const T> data) {
std::ofstream file(filename, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Failed to open file\n";
return;
}
const std::streamsize datasize_bytes = data.size() * sizeof(T);
file.write(
reinterpret_cast<const char *>(data.data()), // NOLINT(*-reinterpret-cast)
datasize_bytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment