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++?
The most efficient is to create a buffer of the correct size and then read the file into the buffer.
Like this:
The statement
can be split into
which is useful if you want to just overwrite the value of an existing std::string variable.
maybe not the most efficient, but reads data in one line:
Here's an iterator-based method.
There should be no
\0
in text files.This depends on a lot of things, such as what is the size of the file, what is its type (text/binary) etc. Some time ago I benchmarked the following function against versions using streambuf iterators - it was about twice as fast: