Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to read Textfile to String [duplicate]

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!

like image 389
danijar Avatar asked Dec 10 '12 14:12

danijar


2 Answers

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>());
like image 126
Benjamin Lindley Avatar answered Sep 28 '22 02:09

Benjamin Lindley


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

like image 37
Dietmar Kühl Avatar answered Sep 28 '22 01:09

Dietmar Kühl