Fseek 不在 C 中设置流的文件位置
Fseek doesn't sets the file position of the stream in C
我制作了这个简单的 C 程序,其目的是计算通过第二个命令行参数给出的文本文件中的字符数。
我面临的问题是 fseek 显示没有响应,结果在函数 "Counter" 中有一个无限循环 (while(!feof(fp)))。通过用 fgetc 替换 fseek,程序工作 fine.My 我的问题是 fseek 出了什么问题。
提前致谢。
#include <stdio.h>
int Counter (FILE * fp);
int main(int argc, char* argv[])
{
int cntr;
FILE * fpc;
fpc = fopen(argv[1],"r");
cntr = Counter(fpc);
fclose(fpc);
printf("%i\n",cntr);
}
int Counter (FILE * fp)
{
int cntr = 0;
while (!feof(fp))
{
cntr++;
fseek(fp,1,1);
}
return cntr;
}
超出文件末尾查找是允许的且定义明确的行为。
这就是为什么 fseek()
不设置文件结束指示符,它甚至会在成功时取消设置。
来自C Standard:
5 After determining the new position, a successful call to the fseek function [...] clears the end-of-file indicator for the stream, and then establishes the new position.
我制作了这个简单的 C 程序,其目的是计算通过第二个命令行参数给出的文本文件中的字符数。 我面临的问题是 fseek 显示没有响应,结果在函数 "Counter" 中有一个无限循环 (while(!feof(fp)))。通过用 fgetc 替换 fseek,程序工作 fine.My 我的问题是 fseek 出了什么问题。 提前致谢。
#include <stdio.h>
int Counter (FILE * fp);
int main(int argc, char* argv[])
{
int cntr;
FILE * fpc;
fpc = fopen(argv[1],"r");
cntr = Counter(fpc);
fclose(fpc);
printf("%i\n",cntr);
}
int Counter (FILE * fp)
{
int cntr = 0;
while (!feof(fp))
{
cntr++;
fseek(fp,1,1);
}
return cntr;
}
超出文件末尾查找是允许的且定义明确的行为。
这就是为什么 fseek()
不设置文件结束指示符,它甚至会在成功时取消设置。
来自C Standard:
5 After determining the new position, a successful call to the fseek function [...] clears the end-of-file indicator for the stream, and then establishes the new position.