refactor: a helper for reading file into bytes
Change-Id: I6fde7ad2de464a7c4d388f7ed67ce5f0e7932bb1
diff --git a/src/ietf-hardware/IETFHardware.cpp b/src/ietf-hardware/IETFHardware.cpp
index e1223c9..bb0a12a 100644
--- a/src/ietf-hardware/IETFHardware.cpp
+++ b/src/ietf-hardware/IETFHardware.cpp
@@ -12,6 +12,7 @@
#include <utility>
#include "IETFHardware.h"
#include "utils/log.h"
+#include "utils/io.h"
using namespace std::literals;
@@ -434,10 +435,7 @@
if (!fs::is_regular_file(filename)) {
throw std::runtime_error{"sysfs entry missing"};
}
- std::ifstream stream;
- stream.exceptions(std::ifstream::badbit | std::ifstream::failbit);
- stream.open(filename, std::ios_base::in | std::ios_base::binary);
- std::vector<uint8_t> buf(std::istreambuf_iterator<char>{stream}, {});
+ auto buf = velia::utils::readFileToBytes(filename);
if (buf.size() != totalSize) {
throw std::runtime_error{fmt::format("expected {} bytes of data, got {}", totalSize, buf.size())};
}
diff --git a/src/utils/io.cpp b/src/utils/io.cpp
index 5de62b2..7ce41a7 100644
--- a/src/utils/io.cpp
+++ b/src/utils/io.cpp
@@ -78,6 +78,14 @@
return std::string(begin, end);
}
+/** @brief Read the entire content of `path` into a vector of bytes */
+std::vector<uint8_t> readFileToBytes(const std::filesystem::path& path)
+{
+ std::ifstream ifs(openStream(path));
+ return {std::istreambuf_iterator<char>{ifs}, {}};
+}
+
+
void writeFile(const std::string& path, const std::string_view& contents)
{
std::ofstream ofs(path);
diff --git a/src/utils/io.h b/src/utils/io.h
index e2ab09b..8df8974 100644
--- a/src/utils/io.h
+++ b/src/utils/io.h
@@ -17,6 +17,7 @@
int64_t readFileInt64(const std::filesystem::path& path);
std::vector<uint32_t> readFileWords(const std::filesystem::path& path, int valuesCount);
std::string readFileToString(const std::filesystem::path& path);
+std::vector<uint8_t> readFileToBytes(const std::filesystem::path& path);
void writeFile(const std::string& path, const std::string_view& contents);
void safeWriteFile(const std::string& filename, const std::string_view& contents);
}