C 库 - feof() 函数



C 库函数 int feof(FILE *stream) 用于测试给定流的文件结束指示符。此函数是标准输入/输出库 (stdio.h) 的一部分,对于以受控方式管理文件读取操作非常重要。

语法

以下是 C 库函数 feof() 的语法:

int feof(FILE *stream);

参数

此函数仅接受一个参数:

  • FILE *stream: 指向 FILE 对象的指针,用于标识要检查的流。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果与流关联的文件结束指示符已设置,则 feof 函数返回非零值。否则,它返回零。

示例 1:直到 EOF 的基本文件读取

此程序从 example.txt 文件读取字符并打印它们,直到 feof 指示文件结尾。

以下是 C 库 feof() 函数的示例。

#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } while (!feof(file)) { char c = fgetc(file); if (feof(file)) break; putchar(c); } fclose(file); return 0; }

输出

以上代码将 example.txt 文件的内容打印到控制台作为结果。

Welcome to tutorials point

示例 2:使用 fgets 读取行直到 EOF

此程序使用 fgets 从 example3.txt 读取行并打印它们,直到 feof 确认已到达文件结尾。

#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } char buffer[256]; while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("%s", buffer); } if (feof(file)) { printf("End of file reached.\n"); } fclose(file); return 0; }

输出

执行上述代码后,将逐行打印 example3.txt 的内容,然后是消息:

End of file reached.
广告