C++ Utilities
5.36.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Toggle main menu visibility
Loading...
Searching...
No Matches
io
misc.cpp
Go to the documentation of this file.
1
#define CPP_UTILITIES_IOMISC_STRING_VIEW
2
3
#include "
./misc.h
"
4
#include "
./nativefilestream.h
"
5
6
#include <iterator>
7
8
using namespace
std
;
9
10
namespace
CppUtilities
{
11
17
std::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)
31
#ifdef __GNUC__
32
#pragma GCC diagnostic push
33
#pragma GCC diagnostic ignored "-Wnull-dereference"
34
#endif
35
res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
36
#ifdef __GNUC__
37
#pragma GCC diagnostic pop
38
#endif
39
return
res;
40
}
41
47
std::string
readFile
(std::string_view path, std::string_view::size_type maxSize)
48
{
49
return
readFile
(std::string(path), maxSize);
50
}
51
58
void
writeFile
(std::string_view path, std::string_view contents)
59
{
60
auto
file =
NativeFileStream
();
61
file.exceptions(ios_base::failbit | ios_base::badbit);
62
file.open(std::string(path), 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
misc.h
CppUtilities
Contains all utilities provided by the c++utilities library.
Definition
argumentparser.h:18
CppUtilities::readFile
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
CppUtilities::NativeFileStream
std::fstream NativeFileStream
Definition
nativefilestream.h:134
CppUtilities::writeFile
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
std
STL namespace.
nativefilestream.h
Generated on
for C++ Utilities by
1.18.0