feof
From cppreference.net
File input/output
| Types and objects | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<stdio.h>
|
||
|
int
feof
(
FILE
*
stream
)
;
|
||
检查给定的文件流是否已到达末尾。
目录 |
参数
| stream | - | 要检查的文件流 |
返回值
若已到达流末尾则返回非零值,否则返回 0
注释
此函数仅报告由最近一次I/O操作所返回的流状态,不会检查关联的数据源。例如,若最近一次I/O操作是
fgetc
且该操作返回了文件的最后一个字节,此时
feof
返回零。随后执行的
fgetc
将执行失败并将流状态更改为
end-of-file
。仅在此后
feof
才会返回非零值。
在典型用法中,输入流处理会在遇到任何错误时停止;随后使用
feof
和
ferror
来区分不同的错误条件。
示例
运行此代码
#include <stdio.h> #include <stdlib.h> int main(void) { const char* fname = "/tmp/unique_name.txt"; // 或使用 tmpnam(NULL); int is_ok = EXIT_FAILURE; FILE* fp = fopen(fname, "w+"); if (!fp) { perror("File opening failed"); return is_ok; } fputs("Hello, world!\n", fp); rewind(fp); int c; // 注意:需使用 int 类型而非 char 类型来处理 EOF while ((c = fgetc(fp)) != EOF) // 标准 C I/O 文件读取循环 putchar(c); if (ferror(fp)) puts("I/O error when reading"); else if (feof(fp)) { puts("End of file is reached successfully"); is_ok = EXIT_SUCCESS; } fclose(fp); remove(fname); return is_ok; }
可能的输出:
Hello, world! End of file is reached successfully