为什么我不能使用 fseek() 访问 EOF?
Why can't I access EOF using fseek()?
#include <stdio.h>
int main()
{
FILE * fp = fopen("Introduce.txt","rt");
fseek(fp,0,SEEK_END);
int i = feof(fp);
printf("%d",i);
fseek(fp,1,SEEK_END);
i = feof(fp);
printf("%d",i);
fseek(fp,-1,SEEK_END);
i = feof(fp);
printf("%d",i);
return 0;
}
我试图在文件末尾访问 EOF 定位 'file position indicator'。
但是这段代码的结果是“000”。
为什么会这样?
feof()
函数不会报告它处于 EOF,直到您尝试读取一些数据并且没有数据可读取。
您可以在打开以写入(或打开以读取和写入)的文件的当前 EOF 之外进行搜索。
请参阅 while (!feof(file))
is always wrong 以了解有关您很少需要使用 feof()
的原因的更多信息。在某些方面,feof()
是一个你应该忘记的函数——如果你假设它不存在,你的大多数程序都会改进。
This documentation on feof
很清楚(强调我的):
This function only reports the stream state as reported by the most
recent I/O operation, it does not examine the associated data source.
For example, if the most recent I/O was a fgetc
, which returned the
last byte of a file, feof
returns zero. The next fgetc
fails and
changes the stream state to end-of-file. Only then feof
returns
non-zero.
In typical usage, input stream processing stops on any error; feof
and
ferror
are then used to distinguish between different error
conditions.
#include <stdio.h>
int main()
{
FILE * fp = fopen("Introduce.txt","rt");
fseek(fp,0,SEEK_END);
int i = feof(fp);
printf("%d",i);
fseek(fp,1,SEEK_END);
i = feof(fp);
printf("%d",i);
fseek(fp,-1,SEEK_END);
i = feof(fp);
printf("%d",i);
return 0;
}
我试图在文件末尾访问 EOF 定位 'file position indicator'。
但是这段代码的结果是“000”。
为什么会这样?
feof()
函数不会报告它处于 EOF,直到您尝试读取一些数据并且没有数据可读取。
您可以在打开以写入(或打开以读取和写入)的文件的当前 EOF 之外进行搜索。
请参阅 while (!feof(file))
is always wrong 以了解有关您很少需要使用 feof()
的原因的更多信息。在某些方面,feof()
是一个你应该忘记的函数——如果你假设它不存在,你的大多数程序都会改进。
This documentation on feof
很清楚(强调我的):
This function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a
fgetc
, which returned the last byte of a file,feof
returns zero. The nextfgetc
fails and changes the stream state to end-of-file. Only thenfeof
returns non-zero.In typical usage, input stream processing stops on any error;
feof
andferror
are then used to distinguish between different error conditions.