C 库 - ferror() 函数



C 库的 ferror(FILE *stream) 函数用于测试给定流的错误指示器。在处理文件操作时,了解可能发生的任何错误非常重要,因为它们可能导致数据损坏、崩溃或未定义的行为。ferror 函数有助于检测此类错误。

语法

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

int ferror(FILE *stream);

参数

  • FILE *stream: 指向 FILE 对象的指针,用于标识要检查错误的流。此流通常来自 fopen 等函数。

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

返回值

如果指定流发生错误,则 ferror 函数返回非零值。如果未发生错误,则返回 0。

示例 1:写入文件后检查错误

此示例尝试将一些文本写入文件。写入后,它使用 ferror 检查是否发生任何错误。

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

#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } fputs("Hello, World!", file); if (ferror(file)) { printf("An error occurred while writing to the file.\n"); } else { printf("Writing to the file was successful.\n"); } fclose(file); return 0; }

输出

以上代码产生以下结果:

Writing to the file was successful.

示例 2:通过过早关闭文件强制发生错误

在此示例中,我们通过关闭文件然后尝试写入文件来强制发生错误。它使用 ferror 检查错误。

#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } fputs("This is a test.", file); fclose(file); // Attempt to write to the closed file fputs("This will cause an error.", file); if (ferror(file)) { printf("An error occurred because the file was already closed.\n"); } else { printf("Writing to the file was successful.\n"); } return 0; }

输出

执行以上代码后,我们得到以下结果:

An error occurred because the file was already closed.
广告