Escualo Escualo - 9 months ago 84
C++ Question

Read whole ASCII file into C++ std::string

I need to read a whole file into memory and place it in a C++


If I were to read it into a
, the answer would be very simple:

std::ifstream t;
int length;"file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension, length); // read the whole file into the buffer
t.close(); // close file handle

// ... Do stuff with buffer here ...

Now, I want to do the exact same thing, but using a
instead of a
. I want to avoid loops, i.e. I don't want to:

std::ifstream t;"file.txt");
std::string buffer;
std::string line;
std::getline(t, line);
// ... Append line to buffer and go on

Any ideas?


Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See:

You can make a streambuf iterator out of the file and initialize the string with it:

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),

Not sure where you're getting the"file.txt", "r") syntax from. As far as I know that's not a method that std::ifstream has. It looks like you've confused it with C's fopen.

Edit: Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.

Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str;

t.seekg(0, std::ios::end);   
t.seekg(0, std::ios::beg);