Fread fwrite text mode read and write carriage return and line feed automatic conversion problem

fread will replace \r\n(0d0a) with \n
fwrite will replace \n with \r\n(0d0a), \r\n will become \r\r\n(0d0d0a)

Today, I am writing a log class for printing information about the service program.

I entered each log message in a single line, so I added a carriage return and line feed at the beginning.
The file is based on the code as follows:
FILE *file = fopen(log_file_name,"a+");
if (!file)return;
fwrite("\r\n",3,file);//This is not the original code, only used explain the problem

Then I checked the hexadecimal data with winhex software, and found that the hexadecimal corresponding to \r\n is 0D 0D 0A.
This is obviously different from what I expected.
Then I checked msdn. The description of fwrite by msdn is that when opening a file in text mode, \r is automatically converted to \r\n when writing, and \n is not processed.
The wrong description of msdn may mislead many people. What msdn is talking about is converting \r, but actually converting \n, which is obtained through actual testing.

Remarks

The Fwrite function writes the size of each item from the buffer to the output stream and calculates it. The file pointer (if any) associated with the stream is incremented by the number of bytes actually written.

If the stream is opened in text mode, each newline character will be replaced with a carriage return line feed pair. This replacement will not affect the return value.

Guess you like

Origin blog.csdn.net/qq_45467083/article/details/112707820