繁体   English   中英

C ++ ifstream,ofstream:原始read()/ write()调用和二进制模式下的打开文件有什么区别?

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

这个问题涉及在向文件读取和写入数据时ifstream和ofstream的行为。

从阅读stackoverflow.com我已经设法找出operator<< (流插入运算符)在输出之前将诸如双精度的对象转换为文本表示,并且调用read()write()读取和写入原始数据,因为它是分别存储在存储器(二进制格式)中。 编辑:这很明显,这里没什么意外。

我还发现以二进​​制模式打开文件会阻止不同操作系统根据需要自动转换换行符。

所以我的问题是:这是自动翻译,例如; 在调用函数read()write()时从\\n\\r\\n发生? 或者这种行为仅适​​用于operator<< (还有operator>> 。)

请注意,这里有一个类似但稍微不那么具体的问题。 它没有给出明确的答案。 使用/不使用ios :: binary模式打开流时使用读/写的区别

二进制和文本模式之间的差异在较低的水平。

如果您在文本模式下打开一个文件,你甚至会在使用会转换数据readwrite操作。

另请注意,只有当位置是从先前的tell (或0)获得时,才允许您在文本文件中seek职位。 为了能够进行随机定位,必须以二进制模式打开文件。

简短回答 - 使用read()和write()时没有完成翻译。 [你的问题的答案是“不。”]

更长的答案 - read()和write()以二进制模式运行,这意味着内容被认为是“二进制数据”。 A \\ n是ASCII 10,10是合法数据值,例如,可以表示数字10。

将\\ n更改为\\ r \\ n的业务是Windows问题。 在Linux中,行尾仅用\\ n标记,不需要翻译。

如果你看一下http://linux.die.net/man/3/fopen上fopen的手册页,那就是这一段

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

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM