diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d1a410..4b5c241 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,6 +28,7 @@ set(HEADER_FILES io/path.h io/catchiofailure.h io/nativefilestream.h + io/misc.h math/math.h misc/memory.h misc/random.h @@ -53,6 +54,7 @@ set(SRC_FILES io/path.cpp io/catchiofailure.cpp io/nativefilestream.cpp + io/misc.cpp math/math.cpp misc/random.cpp tests/testutils.cpp @@ -116,7 +118,7 @@ set(META_APP_AUTHOR "Martchus") set(META_APP_URL "https://github.com/${META_APP_AUTHOR}/${META_PROJECT_NAME}") set(META_APP_DESCRIPTION "Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities") set(META_VERSION_MAJOR 4) -set(META_VERSION_MINOR 5) +set(META_VERSION_MINOR 6) set(META_VERSION_PATCH 0) # find required 3rd party libraries diff --git a/io/misc.cpp b/io/misc.cpp new file mode 100644 index 0000000..5c4245e --- /dev/null +++ b/io/misc.cpp @@ -0,0 +1,33 @@ +#include "./misc.h" +#include "./catchiofailure.h" + +#include +#include + +using namespace std; + +namespace IoUtilities { + +/*! + * \brief Reads all contents of the specified file in a single call. + * \throws Throws std::ios_base::failure when an error occurs or the specified \a maxSize + * would be exceeded. + */ +string readFile(const string &path, std::string::size_type maxSize) +{ + ifstream file; + file.exceptions(ios_base::failbit | ios_base::badbit); + file.open(path, ios_base::in | ios_base::binary); + file.seekg(0, ios_base::end); + string res; + const auto size = static_cast(file.tellg()); + if(maxSize != string::npos && size > maxSize) { + throwIoFailure("File exceeds max size"); + } + res.reserve(size); + file.seekg(ios_base::beg); + res.assign((istreambuf_iterator(file)), istreambuf_iterator()); + return res; +} + +} diff --git a/io/misc.h b/io/misc.h new file mode 100644 index 0000000..88e51fe --- /dev/null +++ b/io/misc.h @@ -0,0 +1,14 @@ +#ifndef IOUTILITIES_MISC_H +#define IOUTILITIES_MISC_H + +#include "../global.h" + +#include + +namespace IoUtilities { + +CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize = std::string::npos); + +} + +#endif // IOUTILITIES_MISC_H