Read file-contents into a string in C++

sonofdelphi picture sonofdelphi · May 26, 2010 · Viewed 204.1k times · Source

Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?

In scripting languages like Perl, it is possible to read a file into a variable in one shot.

    open(FILEHANDLE,$file);
    $content=<FILEHANDLE>;

What would be the most efficient way to do this in C++?

Answer

Maik Beckmann picture Maik Beckmann · May 26, 2010

Like this:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

can be split into

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

which is useful if you want to just overwrite the value of an existing std::string variable.