Browse Source

Add convenience function to read entire file at once

feature/exec_app
Martchus 5 years ago
parent
commit
6115933756
  1. 4
      CMakeLists.txt
  2. 33
      io/misc.cpp
  3. 14
      io/misc.h

4
CMakeLists.txt

@ -28,6 +28,7 @@ set(HEADER_FILES
io/path.h
io/catchiofailure.h
io/nativefilestream.h
io/misc.h
math/math.h
misc/memory.h
misc/random.h
@ -53,6 +54,7 @@ set(SRC_FILES
io/path.cpp
io/catchiofailure.cpp
io/nativefilestream.cpp
io/misc.cpp
math/math.cpp
misc/random.cpp
tests/testutils.cpp
@ -116,7 +118,7 @@ set(META_APP_AUTHOR "Martchus")
set(META_APP_URL "https://github.com/${META_APP_AUTHOR}/${META_PROJECT_NAME}")
set(META_APP_DESCRIPTION "Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities")
set(META_VERSION_MAJOR 4)
set(META_VERSION_MINOR 5)
set(META_VERSION_MINOR 6)
set(META_VERSION_PATCH 0)
# find required 3rd party libraries

33
io/misc.cpp

@ -0,0 +1,33 @@
#include "./misc.h"
#include "./catchiofailure.h"
#include <fstream>
#include <streambuf>
using namespace std;
namespace IoUtilities {
/*!
* \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.
*/
string readFile(const string &path, std::string::size_type maxSize)
{
ifstream file;
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());
if(maxSize != string::npos && size > maxSize) {
throwIoFailure("File exceeds max size");
}
res.reserve(size);
file.seekg(ios_base::beg);
res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
return res;
}
}

14
io/misc.h

@ -0,0 +1,14 @@
#ifndef IOUTILITIES_MISC_H
#define IOUTILITIES_MISC_H
#include "../global.h"
#include <string>
namespace IoUtilities {
CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize = std::string::npos);
}
#endif // IOUTILITIES_MISC_H
Loading…
Cancel
Save