7

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!

1

2 Answers 2

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>()); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.