我有一个名为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
每当遇到\ n时,ftell会跳过一个值,例如它跳过了值7.为什么会这样?请详细解释一下,我想知道。
答案 0 :(得分:1)
问题在于换行符,在Windows中为\r\n
(Does Windows carriage return \r\n consist of two characters or one character?)。
尝试更改这些:
fopen("myfile.txt","r");
到这些:
fopen("myfile.txt","rb");
其中b
用于二进制模式。
二进制模式在Windows上有所不同,其中文本模式将两个字符回车符,换行序列映射到单个换行符。注意:Linux上不需要映射。