[LC++]Copying binary files with operator<< and rdbuf()

Chris Vine chris at cvine.freeserve.co.uk
Sun Nov 23 20:22:01 UTC 2003


On Saturday 22 November 2003 6:23 am, Carlo Wood wrote:
> On Fri, Nov 21, 2003 at 06:06:51PM -0800, Brian Nelson wrote:
> > Even the overloaded operator<< for streambufs?
>
> Nah, that should just copy the buffer over
> to the target buffer.  Can't involve additional
> formatting imho.

Which means that, to answer the original poster's question, operators << and 
>> can be used for a binary transfer of data from a streambuf to an ostream 
and to a streambuf from an istream respectively, and is generally the most 
efficient way of copying an entire file if you do not want to use the write() 
and read() primitives provided by the OS.  In the case of streambufs, << and 
>> do not imply formatting.  From that point of view, it may have been better 
to have chosen a different operator.

In other words, if 'in' and 'out' are objects of type ifstream and ofstream, 
the following will make a straight binary copy of a file:

out << in.rdbuf();

See for example section 13.14.3 of Josuttis's "The Standard C++ Library".

Chris.




More information about the tuxCPProgramming mailing list