C++ Utilities 5.37.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
misc.cpp
Go to the documentation of this file.
1#define CPP_UTILITIES_IOMISC_STRING_VIEW
2
3#include "./misc.h"
5
6#include <iterator>
7
8using namespace std;
9
10namespace CppUtilities {
11
17std::string readFile(const std::string &path, std::string::size_type maxSize)
18{
19 auto file = NativeFileStream();
20 file.exceptions(ios_base::failbit | ios_base::badbit);
21 file.open(path, ios_base::in | ios_base::binary);
22 file.seekg(0, ios_base::end);
23 string res;
24 const auto size = static_cast<string::size_type>(file.tellg());
25 if (maxSize != string::npos && size > maxSize) {
26 throw ios_base::failure("File exceeds max size");
27 }
28 res.reserve(size);
29 file.seekg(ios_base::beg);
30 // ignore warning about null pointer dereference from GCC 12 for now (which is *likely* not correct)
32 CPP_UTILITIES_WARNING_DISABLE("-Wnull-dereference")
33 res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
35 return res;
36}
37
43std::string readFile(std::string_view path, std::string_view::size_type maxSize)
44{
45 return readFile(std::string(path), maxSize);
46}
47
54void writeFile(std::string_view path, std::string_view contents)
55{
56 auto file = NativeFileStream();
57 file.exceptions(ios_base::failbit | ios_base::badbit);
58 file.open(std::string(path), ios_base::out | ios_base::trunc | ios_base::binary);
59 file.write(contents.data(), static_cast<std::streamoff>(contents.size()));
60 file.close();
61}
62
63} // namespace CppUtilities
#define CPP_UTILITIES_WARNING_PUSH
Causes GCC/Clang to remember the state of the diagnostics.
Definition global.h:154
#define CPP_UTILITIES_WARNING_POP
Causes GCC/Clang to restore the previous state of the diagnostics.
Definition global.h:155
#define CPP_UTILITIES_WARNING_DISABLE(text)
Causes GCC/Clang to suppress the specified diagnostic.
Definition global.h:156
Contains all utilities provided by the c++utilities library.
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:17
std::fstream NativeFileStream
CPP_UTILITIES_EXPORT void writeFile(std::string_view path, std::string_view contents)
Writes all contents to the specified file in a single call.
Definition misc.cpp:54
STL namespace.