6

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!

Community
  • 1
  • 1
danijar
  • 27,743
  • 34
  • 143
  • 257
  • 1
    http://stackoverflow.com/a/4761779/942596 this links gives a nice method. replace vector with string and it still works. – andre Dec 10 '12 at 14:16

2 Answers2

8

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>());
Benjamin Lindley
  • 95,516
  • 8
  • 172
  • 256
1

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

Dietmar Kühl
  • 141,209
  • 12
  • 196
  • 356