carriage return by fgets

前端 未结 2 748
醉话见心
醉话见心 2020-12-06 07:08

I am running the following code:

#include
#include
#include

int main(){
    FILE *fp;
    if((fp=fopen(\"test.txt         


        
2条回答
  •  渐次进展
    2020-12-06 07:44

    Since I am on Windows, it takes \r\n as a new line character...

    This assumption is wrong. The C standard treats carriage return and new line as two different things, as evidenced in C99 §5.2.1/3 (Character sets):

    [...] In the basic execution character set, there shall be control characters representing alert, backspace, carriage return, and new-line. [...]

    The fgets function description is as follows, in C99 §7.19.7.2/2:

    The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

    Therefore, when encountering the string I am a boy\r\n, a conforming implementation should read up to the \n character. There is no possibly sane reason why the implementation should discard \r based on the platform.

提交回复
热议问题