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++?
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.