The newline difference between text file and console

Hi guys, i know that newline character in text file is 2 bytes which is CR(\r) and LF(\n). But why does the program read it as 1 byte only?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
    FILE *file_a;
    char character[30];
    int baca_c,loop;

    file_a=fopen("character.txt","rt");

    if(file_a==NULL){
        printf("File could not be opened: %s", strerror(errno));
        return 1;
    }

    do{
        baca_c=fread(character,1,30,file_a);
        for(loop=0;loop<baca_c;loop++)printf("%c",character[loop]);
    }while (baca_c>0);

    fclose(file_a);

    return 0;
}
If you open a file in text mode, which you are, the runtime performs a newline conversion so the program behaves consistently across platforms when dealing with text files for that platform.

Note that CRLF is the newline sequence only on Windows. On Linux, BSDs, OSX, and other unixes, the sequence is LF, while on MacOS prior to 10.0 the sequence was CR.
Last edited on
Well, i try to open the file in binary mode and the program reads it as 2 bytes.
So, does this thing can affect the platform dependency of the program?
Last edited on
That depends on what exactly you're trying to do with the file. There's no easy answer to your question.
Well, thanks.

I'm little bit curious, what should i write when i want to write a newline to text file in windows?

Should i use \n only if i open the file using text mode?
And if i open it in binary mode, should i use both \r and \n?
Last edited on
Topic archived. No new replies allowed.