P
Pavel
Just a nit-pick: std::string is not guaranteed to be stored contiguously soJuha said:Luca Risolia said:int main(int argc, char** argv) {
ifstream f(argv[1], ifstream::in | ifstream::binary);
istreambuf_iterator<char> i(f), eof;
string s(i, eof);
cout<< s;
}
Note that this is not the fastest possible way of reading a large file
because reading one byte at a time from a C++ stream is pretty slow.
If maximum reading speed is required, the best compromise between speed
and relative ease of usage is to use std::fread() instead. It would go
something like this:
std::FILE* inFile = std::fopen(argv[1], "rb");
if(!inFile) { std:error(argv[1]); return 1; }
std::fseek(inFile, 0, SEEK_END);
std::string s(std::ftell(inFile), ' ');
std::rewind(inFile);
std::fread(&s[0], 1, s.length(), inFile);
technically your code has UB.
std::fclose(inFile);
For example in my system reading a 700-megabyte file takes about 7.5 seconds
by using the istreambuf_iterator method, while with fread it takes about
1.5 seconds.
(If maximum reading speed is not imperative, or if input files are
expected to be small, then use whichever method is safest and most
convenient.)
-Pavel