C++ Utilities 5.24.7
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 <streambuf>
7
8using namespace std;
9
10namespace CppUtilities {
11
17std::string readFile(const std::string &path, std::string::size_type maxSize)
18{
19 return readFile(std::string_view(path), maxSize);
20}
21
27std::string readFile(std::string_view path, std::string_view::size_type maxSize)
28{
30 file.exceptions(ios_base::failbit | ios_base::badbit);
31 file.open(path.data(), ios_base::in | ios_base::binary);
32 file.seekg(0, ios_base::end);
33 string res;
34 const auto size = static_cast<string::size_type>(file.tellg());
35 if (maxSize != string::npos && size > maxSize) {
36 throw ios_base::failure("File exceeds max size");
37 }
38 res.reserve(size);
39 file.seekg(ios_base::beg);
40 // ignore warning about null pointer dereference from GCC 12 for now (which is *likely* not correct)
41#ifdef __GNUC__
42#pragma GCC diagnostic push
43#pragma GCC diagnostic ignored "-Wnull-dereference"
44#endif
46#ifdef __GNUC__
47#pragma GCC diagnostic pop
48#endif
49 return res;
50}
51
58void writeFile(std::string_view path, std::string_view contents)
59{
61 file.exceptions(ios_base::failbit | ios_base::badbit);
62 file.open(path.data(), ios_base::out | ios_base::trunc | ios_base::binary);
63 file.write(contents.data(), static_cast<std::streamoff>(contents.size()));
64 file.close();
65}
66
67} // namespace CppUtilities
Contains all utilities provides 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
IntegralType stringToNumber(const StringType &string, BaseType base=10)
Converts the given string to an unsigned/signed number assuming string uses the specified base.
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:58
STL namespace.