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
The shortest variant: Live On Coliru
std::string str(std::istreambuf_iterator{ifs}, {});
It requires the header
.
There were some reports that this method is slower than preallocating the string and using std::istream::read
. However, on a modern compiler with optimisations enabled this no longer seems to be the case, though the relative performance of various methods seems to be highly compiler dependent.