问题描述:

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

网友答案:

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.

网友答案:

Short answer -- no translation done when using read() & write(). [The answer to your question is "no."]

Longer answer -- read() & write() operate in binary mode which means that the contents are considered to be "binary data." A \n is an ASCII 10 and 10 is a legitimate data value that could, for instance, represent the number 10.

This business of changing \n to \r\n is a Windows issue. In Linux, end of line is marked simply with \n and no translation is needed.

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

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.)

Hopefully that will help.

相关阅读:
Top