簡體   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