这个问题已经有了答案:
Why does ftell() shows wrong position after fread()?
3个答案
我有一个名为myfile.txt的文本文件:

line 1
l

我的代码:
#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;
}

输出为:
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      

每当遇到一个值时,ftell将跳过一个值,例如它跳过了值7。为什么会这样?请详细解释我,我想知道。

最佳答案

问题在于换行符,在windows中是\r\nDoes Windows carriage return \r\n consist of two characters or one character?)。
尝试更改这些:

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

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

其中b表示二进制模式。
在文本模式将两个字符的回车换行序列映射到一个新的行字符的窗口中,二进制模式起到了作用。注意:Linux上不需要映射。

10-04 14:16