Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?
I assumed there would be a question like this already, but I couldn't find one. So here goes my question.
What is the shortest way to read a whole text file into a string? I only want to use features of the newest C++ standard and standard libraries.
I think there must be an one liner for this common task!
Probably this:
std::ifstream fin("filename");
std::ostringstream oss;
oss << fin.rdbuf();
std::string file_contents = oss.str();
There's also this:
std::istreambuf_iterator<char> begin(fin), end;
std::string file_contents(begin, end);
Some might suggest this, but I prefer to type istreambuf_iterator<char>
only once.
std::string file_contents(std::istreambuf_iterator<char>{fin}, std::istreambuf_iterator<char>());
To read a file into a std::string
using one statement (whether it fit on one line depends on the length of you lines...) looks like this:
std::string value{
std::istreambuf_iterator<char>(
std::ifstream("file.txt").rdbuf()),
std::istreambuf_iterator<char>()};
The approach is unfortunately often not as fast as using an extra std::ostringstream
is (although it should really be faster...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With