C ++ ifstream, ofstream: What is the difference between calling raw read () / write () and opening a file in binary mode?

This question relates to the behavior of ifstream and stream when reading and writing data to files.

From reading around stackoverflow.com, I was able to find out that operator<< (the stream insert operator) converts objects such as duplicates into a text representation before exiting, and calls read() and write() read and write raw data since it is stored in memory (binary format), respectively. EDIT: This is very obvious, nothing unexpected here.

I also found that opening a file in binary mode prevents the automatic translation of newline characters in accordance with the requirements of various operating systems.

So my question is this: does this automatic translation, for example; from \n to \r\n occur when calling the read() and write() functions? Or this behavior is just characteristic of operator<< . (And also operator>> .)

Please note that there is a similar, but slightly less specific question. This does not give a definite answer. Difference in read / write usage when opening a stream with / without ios :: binary mode

+5
source share
2 answers

The difference between binary and text modes is lower.

If you open the file in text mode, you will receive translated data even when using read and write operations.

Also note that you are allowed to seek a position in a text file only if the position was obtained from a previous tell (or 0). To be able to do arbitrary positioning, the file had to be opened in binary mode.

+4
source

The short answer is that using read () and write () does not translate. [The answer to your question is no.]

A longer answer - read () and write () work in binary mode, which means that the content is considered β€œbinary data”. A \ n is ASCII 10 and 10 is a legitimate data value, which may, for example, represent the number 10.

This operation changing \ n to \ r \ n is a Windows problem. On Linux, the end of the line is simply marked \ n and no translation is required.

If you look at the manual page for fopen at http://linux.die.net/man/3/fopen , this paragraph is there

 The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.) 

Hope this helps.

-2
source

All Articles