std::ifstream f("file.txt");
if (f)
{
std::stringstream buffer;
buffer << f.rdbuf();
f.close();
// The content of "file.txt" is available in the string `buffer.str()`
}
The rdbuf()
method returns a pointer to a streambuf
that can be pushed into buffer
via the stringstream::operator<<
member function.
Another possibility (popularized in Effective STL by Scott Meyers) is:
std::ifstream f("file.txt");
if (f)
{
std::string str((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
// Operations on `str`...
}
This is nice because requires little code (and allows reading a file directly into any STL container, not only strings) but can be slow for big files.
NOTE: the extra parentheses around the first argument to the string constructor are essential to prevent the most vexing parse problem.
Last but not least:
std::ifstream f("file.txt");
if (f)
{
f.seekg(0, std::ios::end);
const auto size = f.tellg();
std::string str(size, ' ');
f.seekg(0);
f.read(&str[0], size);
f.close();
// Operations on `str`...
}
which is probably the fastest option (among the three proposed).