Sunday, February 17, 2008

Reading file all at once

Few times, you would want to read the whole file in one go, not line by line, not by a fixed buffer size. Here's a way to get that done:

    std::fstream ifs("filename.txt");
    if (!ifs)
    {
         std::stringstream oss;
         oss << ifs.rdbuf();
    }

As simple as that. The contents of the file are moved (re-directed) to the stringstream. The same code can be used to make copies of files. You would need to replace the stringstream object with an fstream one though.

1 comment:

haystack said...

Nice code (this been a Google result for a long time), but I'm pretty sure your if-statement is incorrect (inverted).

It should be:
if(ifs) not if(!ifs)

or:
if(ifs.is_open())