cfilefopenfgetcftell

Why does ftell skips some positions in the file?


I have a text file named myfile.txt which reads:

line 1
l

My code:

#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;
}

The output is :

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, the ftell skips one value for example it has skipped the value 7. Why is it so? Please explain me in detail, I want to know.


Solution

  • The problem lies in the newline character, which in Windows is \r\n (Does Windows carriage return \r\n consist of two characters or one character?).

    Try changing these:

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

    to these:

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

    where b is for binary mode.

    Binary mode makes a difference on Windows where text mode maps the two character carriage return, line feed sequence to a single new-line character. Note: No mapping is needed on Linux.