Reading text file into a std::string

suggest change
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).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


File I/O:
* Reading text file into a std::string

Table Of Contents
8 Arrays
11 Loops
38 File I/O
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype