Last active
September 9, 2024 17:05
-
-
Save kwsp/5d15c81d97749536fe1785e499c7dc02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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