C++ Utilities  4.17.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
misc.cpp
Go to the documentation of this file.
1 #include "./misc.h"
2 #include "./catchiofailure.h"
3 #include "./nativefilestream.h"
4 
5 #include <streambuf>
6 
7 using namespace std;
8 
9 namespace IoUtilities {
10 
16 string readFile(const string &path, std::string::size_type maxSize)
17 {
18  NativeFileStream file;
19  file.exceptions(ios_base::failbit | ios_base::badbit);
20  file.open(path, ios_base::in | ios_base::binary);
21  file.seekg(0, ios_base::end);
22  string res;
23  const auto size = static_cast<string::size_type>(file.tellg());
24  if (maxSize != string::npos && size > maxSize) {
25  throwIoFailure("File exceeds max size");
26  }
27  res.reserve(size);
28  file.seekg(ios_base::beg);
29  res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
30  return res;
31 }
32 } // namespace IoUtilities
CPP_UTILITIES_EXPORT void throwIoFailure(const char *what)
Throws an std::ios_base::failure with the specified message.
std::fstream NativeFileStream
CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize=std::string::npos)
Reads all contents of the specified file in a single call.
Definition: misc.cpp:16
Contains utility classes helping to read and write streams.
Definition: binaryreader.h:10