feof
来自 cppreference.cn
定义于头文件 <stdio.h> |
||
int feof( FILE *stream ); |
||
检查是否已到达给定文件流的末尾。
内容 |
[编辑] 参数
stream | - | 要检查的文件流 |
[编辑] 返回值
如果已到达流的末尾,则为非零值,否则为 0
[编辑] 注释
此函数仅报告最近一次 I/O 操作报告的流状态,它不检查关联的数据源。例如,如果最近一次 I/O 是 fgetc,它返回文件的最后一个字节,则 feof
返回零。 下一个 fgetc 失败并将流状态更改为文件结尾。 只有那时 feof
才返回非零值。
在典型用法中,输入流处理会在任何错误时停止; 然后使用 feof
和 ferror 来区分不同的错误情况。
[编辑] 示例
运行此代码
#include <stdio.h> #include <stdlib.h> int main(void) { const char* fname = "/tmp/unique_name.txt"; // or 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; // note: int, not char, required to handle EOF while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop 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