C++ Utilities
5.37.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
CPP_UTILITIES_WARNING_PUSH
32
CPP_UTILITIES_WARNING_DISABLE
(
"-Wnull-dereference"
)
33
res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
34
CPP_UTILITIES_WARNING_POP
35
return
res;
36
}
37
43
std::string
readFile
(std::string_view path, std::string_view::size_type maxSize)
44
{
45
return
readFile
(std::string(path), maxSize);
46
}
47
54
void
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
CPP_UTILITIES_WARNING_PUSH
#define CPP_UTILITIES_WARNING_PUSH
Causes GCC/Clang to remember the state of the diagnostics.
Definition
global.h:154
CPP_UTILITIES_WARNING_POP
#define CPP_UTILITIES_WARNING_POP
Causes GCC/Clang to restore the previous state of the diagnostics.
Definition
global.h:155
CPP_UTILITIES_WARNING_DISABLE
#define CPP_UTILITIES_WARNING_DISABLE(text)
Causes GCC/Clang to suppress the specified diagnostic.
Definition
global.h:156
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:54
std
STL namespace.
nativefilestream.h
Generated on
for C++ Utilities by
1.18.0