问题
在使用 fscanf读取文件时,使用[^\n]格式读到行末时,fscanf返回为0,不等于EOF(-1),所以一直执行while循环,打印str(第一行数据)。现在在循环体中调用fseek,使fscan读到行末时强行跳过/n,从而能够读取后面行的数据,现在的问题是,fseek中的offset为什么是2不是1呢?\n不是只有一个长度吗?
代码
文件内容如下
#include <stdio.h>
int main()
{
char str[1024];
// char str2[1024];
FILE *fp = fopen("./test.txt", "r");
while (fscanf(fp, "%[^\n]", str)!=EOF)
{
printf("%s\n", str);
fseek(fp,2,SEEK_CUR);
}
fclose(fp);
return 0;
}
执行结果:
fseek(fp,2,SEEK_CUR)可以得到正确的结果,fseek(fp,1,SEEK_CUR)则是一直打印第一行结果。