Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 817
FreelanceConsultant Avatar asked Nov 01 '22 02:11

FreelanceConsultant


1 Answers

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.

like image 51
6502 Avatar answered Nov 15 '22 05:11

6502