Why does ftell skip some positions in the file?

I have a text file called myfile.txt that states:

line 1
l

My code is:

#include<stdio.h>
int main(){
    FILE *f = fopen("myfile.txt","r");
    if(f==NULL){
        FILE *fp=fopen("myfile.txt","w");
        fclose(fp);
        f = fopen("myfile.txt","r");
    }
    while(!feof(f)){
        printf("\ncharacter number %d    ",ftell(f));
        putchar(fgetc(f));      
    }
    fclose(f);
    return 0;
}

Conclusion:

character number 0    l
character number 1    i
character number 2    n
character number 3    e
character number 4
character number 5    1
character number 6

character number 8    l
character number 9      

Whenever a \ n is encountered, ftell skips a single value, for example, it skips a value 7. Why is this so? Please explain to me in detail, I want to know.

+4
source share
1 answer

The problem is the newline character that is on Windows \r\n( Does the Windows carriage return \ r \ n of two characters or one character? ).

Try changing them:

fopen("myfile.txt","r");

to them:

fopen("myfile.txt","rb");

where bfor binary mode.

Windows, , . . Linux .

+1

Source: https://habr.com/ru/post/1686004/


All Articles