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函数将每个项的大小缓冲区写入到输出, 并对其进行计算。 关联的文件指针 (如果有) 以实际写入的字节数为增量递增。 

如果在文本模式下打开, 则会将每个换行符替换为回车换行符对。 该替换不会影响返回值。

 

posted @ 2019-09-05 15:42  乘于时  阅读(2951)  评论(0编辑  收藏  举报