C++ ifstream, ofstream: What's the difference between raw read()/write() calls and opening file in binary mode?

1.6k views Asked by At

This question concerns the behaviour of ifstream and ofstream when reading and writing data to files.

From reading around stackoverflow.com I have managed to find out that operator<< (stream insertion operator) converts objects such as doubles to text representation before output, and calls to read() and write() read and write raw data as it is stored in memory (binary format) respectively. EDIT: This much is obvious, nothing unexpected here.

I also found out that opening a file in binary mode prevents automatic translation of newline characters as required by different operating systems.

So my question is this: Does this automatic translation, eg; from \n to \r\n occur when calling functions read() and write()? Or is this behaviour just specific to the operator<<. (And also operator>>.)

Note there is a similar but slightly less specific question here. It does not give a definite answer. Difference in using read/write when stream is opened with/without ios::binary mode

1

There are 1 answers

0
6502 On BEST ANSWER

The difference between binary and text mode its at a lower level.

If you open a file in text mode you will get translated data even when using read and write operations.

Please also note that you're allowed to seek to a position in a text file only if the position was obtained from a previous tell (or 0). To be able to do random positioning, the file must have been opened in binary mode.