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。
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函数将每个项的大小从缓冲区写入到输出流, 并对其进行计算。 与流关联的文件指针 (如果有) 以实际写入的字节数为增量递增。
如果在文本模式下打开流, 则会将每个换行符替换为回车换行符对。 该替换不会影响返回值。