What the point of using std::ios_base::binary?

The differences between binary and text modes are implementation
defined, but only concern the lowest level: they do not change the
meaning of things like << and >> (which insert and extract textual
data). Also, formally, outputting all but a few non-printable
characters (like '\n') is undefined behavior if the file is in text
mode.

For the most common OSs: under Unix, there is no distinction; both are
identical. Under Windows, '\n' internally will be mapped to the two
character sequence CR, LF (0x0D, 0x0A) externally, and 0x1A will be
interpreted as an end of file when reading. In more exotic (and mostly
extinct) OSs, however, they could be represented by entirely different
file types at the OS level, and it could be impossible to read a file in
text mode if it were written in binary mode, and vice versa. Or you
could see something different: extra white space at the end of line, or
no '\n' in binary mode.

With regards to always setting std::ios_base::binary: my policy for
portable files is to decide exactly how I want them formatted, set
binary, and output what I want. Which is often CR, LF, rather than just
LF, since that’s the network standard. On the other hand, most
Windows programs have no problems with just LF, but I’ve encountered
more than a few Unix programs which have problems with CR, LF; which
argues for systematically using just LF (which is easier, too). Doing
things this way means that I get the same results regardless of whether
I’m running under Unix or under Windows.

Leave a Comment