Carriage Return by fgets

I run the following code:

#include<stdio.h>
#include<string.h>
#include<io.h>

int main(){
    FILE *fp;
    if((fp=fopen("test.txt","r"))==NULL){
        printf("File can't be read\n");
        exit(1);
    }
    char str[50];
    fgets(str,50,fp);
    printf("%s",str);
    return 0;
}

text.txt contains: I am a boy\r\n

Since I am on Windows, it takes \ r \ n as a newline character, so if I read this from a file, it should be stored "I am a boy\n\0"in str, but I get "I am a boy\r\n". I am using the mingw compiler.

+5
source share
2 answers

Since I am on Windows, it takes \ r \ n as the newline character ...

This assumption is incorrect. Standard C treats carriage returns and newlines as two different things, as evidenced by C99 §5.2.1 / 3 (character sets):

[...] The base execution character set must have control characters representing a warning, backspace, carriage return, and new line. [...]

fgets : C99 §7.19.7.2/2:

fgets , , n , , s. ( ) . , .

, I am a boy\r\n, \n. , \r .

+4

c fopen. . MSDN fopen (fopen MSDN):

b - () ; , , .

, Microsoft c , "b", .

mingw, , , GNU c, POSIX. , GNU fopen (fopen gnu.org):

'b opentype ; , . POSIX ( GNU).

: "b" char, . Windows, GNU c, . fgets , .

+5

All Articles