From 7c5566a616c783377d1e9e8db8eeb81ccae40db6 Mon Sep 17 00:00:00 2001 From: Thomas Fischer <thomas.fischer@ufz.de> Date: Thu, 26 Sep 2013 10:44:50 +0200 Subject: [PATCH] [FileTools.h] Added readBinaryArray(). --- BaseLib/FileTools.h | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/BaseLib/FileTools.h b/BaseLib/FileTools.h index b85c56e9c24..90864ecb856 100644 --- a/BaseLib/FileTools.h +++ b/BaseLib/FileTools.h @@ -17,6 +17,10 @@ #include <fstream> #include <string> +#include <vector> + +// ThirdParty/logog +#include "logog/include/logog.hpp" namespace BaseLib { @@ -66,6 +70,35 @@ T readBinaryValue(std::istream& in) return v; } +template <typename T> +std::vector<T> readBinaryArray(std::string const& filename, std::size_t const n) +{ + std::ifstream in(filename.c_str()); + if (!in) { + ERR("readBinaryArray(): Error while reading from file \"%s\".", filename.c_str()); + ERR("Could not open file \"%s\" for input.", filename.c_str()); + in.close(); + return std::vector<T>(); + } + + std::vector<T> result; + result.reserve(n); + + for (std::size_t p = 0; in && !in.eof() && p < n; ++p) + result.push_back(BaseLib::readBinaryValue<T>(in)); + + if (result.size() == n) + return result; + + ERR("readBinaryArray(): Error while reading from file \"%s\".", filename.c_str()); + ERR("Read different number of values. Expected %d, got %d.", n, result.size()); + + if (!in.eof()) + ERR("EOF reached.\n"); + + return std::vector<T>(); +} + /** * \brief truncate a file * -- GitLab