2017-02-03 00:55:15 +01:00
|
|
|
#include "./misc.h"
|
2018-09-29 18:05:02 +02:00
|
|
|
#include "./nativefilestream.h"
|
2017-02-03 00:55:15 +01:00
|
|
|
|
|
|
|
#include <streambuf>
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
2019-06-10 21:56:46 +02:00
|
|
|
namespace CppUtilities {
|
2017-02-03 00:55:15 +01:00
|
|
|
|
|
|
|
/*!
|
|
|
|
* \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.
|
|
|
|
*/
|
2019-06-01 15:07:08 +02:00
|
|
|
std::string readFile(const std::string &path, std::string::size_type maxSize)
|
2017-02-03 00:55:15 +01:00
|
|
|
{
|
2018-09-29 18:05:02 +02:00
|
|
|
NativeFileStream file;
|
2017-02-03 00:55:15 +01:00
|
|
|
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<string::size_type>(file.tellg());
|
2017-05-01 03:13:11 +02:00
|
|
|
if (maxSize != string::npos && size > maxSize) {
|
2018-10-04 18:07:30 +02:00
|
|
|
throw ios_base::failure("File exceeds max size");
|
2017-02-03 00:55:15 +01:00
|
|
|
}
|
|
|
|
res.reserve(size);
|
|
|
|
file.seekg(ios_base::beg);
|
|
|
|
res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
|
|
|
|
return res;
|
|
|
|
}
|
2019-06-10 21:56:46 +02:00
|
|
|
} // namespace CppUtilities
|