How do I read a file into a std::string
, i.e., read the whole file at once?
Text or binary mode should be specified by the caller. The solution should b
If you have C++17 (std::filesystem), there is also this way (which gets the file's size through std::filesystem::file_size
instead of seekg
and tellg
):
#include
#include
#include
namespace fs = std::filesystem;
std::string readFile(fs::path path)
{
// Open the stream to 'lock' the file.
std::ifstream f(path, std::ios::in | std::ios::binary);
// Obtain the size of the file.
const auto sz = fs::file_size(path);
// Create a buffer.
std::string result(sz, '\0');
// Read the whole file into the buffer.
f.read(result.data(), sz);
return result;
}
Note: you may need to use
and std::experimental::filesystem
if your standard library doesn't yet fully support C++17. You might also need to replace result.data()
with &result[0]
if it doesn't support non-const std::basic_string data.