fread fwrite文本模式讀寫回車換行符 自動轉換問題


fread  會把\r\n(0d0a)替換為\n
fwrite 會把\n替換為\r\n(0d0a),\r\n會變成\r\r\n(0d0d0a)

 

今天在寫一個日志類,用於打印服務程序的信息。

我將每一個日志信息都以單行的形式輸入,所以在開頭加上了回車換行符。
文件是以代碼如下:
FILE *file = fopen(log_file_name,"a+"); if (!file)return; fwrite("\r\n",3,file);//這里不是原始代碼,只用來說明問題

然后用winhex軟件查看了十六進制的數據,結果發現\r\n對應的十六進制為0D 0D 0A。
這很明顯,和我的預期不一樣。
然后查看了msdn,msdn對於fwrite的描述是,以文本模式打開文件的時候,寫入時會自動將\r轉換為\r\n,不對\n進行處理。
msdn的錯誤描述,可能會誤導很多人吧。msdn說的是對\r進行轉換,其實是對\n進行轉換,經過實際測試得到的。
 
下面是2008-MSDN:

Remarks

The fwrite function writes up to count items, of size length each, from buffer to the output stream.

The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written.

If stream is opened in text mode, each carriage return is replaced with a carriage-return – linefeed pair.

The replacement has no effect on the return value. 

 

下面是在線-MSDN: 修正了上面的錯誤

Remarks

The fwrite function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written. If stream is opened in text mode, each line feed is replaced with a carriage return-line feed pair. The replacement has no effect on the return value.

When stream is opened in Unicode translation mode—for example, if stream is opened by calling fopen and using a mode parameter that includes ccs=UNICODE, ccs=UTF-16LE, or ccs=UTF-8, or if the mode is changed to a Unicode translation mode by using _setmode and a mode parameter that includes _O_WTEXT, _O_U16TEXT, or _O_U8TEXT—buffer is interpreted as a pointer to an array of wchar_t that contains UTF-16 data. An attempt to write an odd number of bytes in this mode causes a parameter validation error.

Because this function locks the calling thread, it is thread-safe. For a non-locking version, see _fwrite_nolock.

 

備注

 

Fwrite函數將每個項的大小緩沖區寫入到輸出, 並對其進行計算。 關聯的文件指針 (如果有) 以實際寫入的字節數為增量遞增。 

如果在文本模式下打開, 則會將每個換行符替換為回車換行符對。 該替換不會影響返回值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM