Reading text file into a std::string
suggest changestd::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 it 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`...
}
In text mode, tellg is not required to be a character count, and it returns -1 on failure. A failed or negative position cannot be used as the string length. This also needs contiguous std::string storage, guaranteed since C++11, and a positive size so that &str[0] refers to a character.
which is probably the fastest option (among the three proposed).