I need a cross-platform, no external library, way of copying a file. In my first pass I came up with (error handling omitted):
char buffer[LEN];
ifstream src(srcFile, ios::in | ios::binary);
ofstream dest(destFile, ios::out | ios::binary);
while (!src.eof()) {
src.read(buffer, LEN);
dest.write(buffer, src.gcount());
}
This worked nicely and I knew exactly what it was doing.
Then I found a post on stackoverflow (sorry, can't find a link right now) that says I can replace all of the above code with:
dest << src.rdbuf();
Which is nice and compact, but hides a lot about what it's doing. It also turns out to be really slow because the implementation of ofstream::operator<<(streambuf) moves things 1 character at a time (using snetxc()/sputc()).
Is there a way for me to make this method faster? Is there a drawback to my original method?
Update: There's something inefficient about using operator<<(streambuf) on windows. The .read()/.write() loop looks to always perform better than operator<<.
Also, changing the size of the buffer in the code above does not affect the size of the reads and writes to the hard drive. To do that you need to set the buffers using stream.rdbuf()->pubsetbuf().