Search code examples
c++iostreamstandard-library

C++ fstream << and >> operators with binary data


I've always read and been told that when dealing with binary files that one should use read() and write() as opposed to the << and >> operators as they are meant for use with formatted data. I've also read that it is possible to use them, but it is an advanced topic, which I can't find where anyone dives into and discusses.

I recently saw some code which did the following:

 std::ifstream file1("x", ios_base::in | ios_base::binary);
 std::ofstream file2("y", ios_base::app | ios_base::binary);

 file1 << file2.rdbuf();

When I pointed out the use of the << operator with the binary file, I was told that the rdbuf() call returns a streambuf * and that << overloads the streambuf* and does a direct copy with no formatting and is thus safe.

Is this true and also safe? How about efficiency? Any gotchas? Details would be much appreciated.

Thanks!


Solution

  • Yes (see 27.6.2.5.3/6 where the overload of << for streambuf is described).