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

Brian Nelson nelson at bignachos.com
Fri Nov 21 16:18:01 UTC 2003


Is it safe to copy a binary file with:

  ifstream fromFile("thisFile", ios_base::binary);
  ofstream toFile ("thatFile", ios_base::binary);
  toFile << fromFile.rdbuf();

The reason I ask is that
http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#3 says:

  The first and most important thing to remember about binary I/O is
  that opening a file with ios::binary is not, repeat not, the only
  thing you have to do. It is not a silver bullet, and will not allow
  you to use the <</>> operators of the normal fstreams to do binary
  I/O.
  [...]
  Opening a file in binary mode disables this conversion, so reading a
  CRLF sequence under Windows won't accidentally get mapped to a '\n'
  character, etc. Binary mode is not supposed to suddenly give you a
  bitstream, and if it is doing so in your program then you've
  discovered a bug in your vendor's compiler...
  [...]
  Second, using << to write and >> to read isn't going to work with the
  standard file stream classes, even if you use skipws during
  reading. Why not? Because ifstream and ofstream exist for the purpose
  of formatting, not reading and writing. Their job is to interpret the
  data into text characters, and that's exactly what you don't want to
  happen during binary I/O.

Though it later says:

  "Use streambufs, that's what they're there for."

So, uhhh, is it OK to use operator<<(basic_streambuf...) ?  To me the
above says both yes and no.

Stroustrup says:

  It is possible to use << to write a streambuf directly into an
  ostream.  This is primarily handy for implementers of I/O mechanisms.

Isn't that exactly what I'm trying to do?

If I can't safely use fstreams to copy a binary file, what is a better
way?

-- 
Don't worry, it's *in*-flammable.



More information about the tuxCPProgramming mailing list