温馨提示×

Linux中fflush的错误处理方式

小樊
82
2024-08-28 21:13:17
栏目: 智能运维

在 Linux 系统中,fflush() 函数用于刷新输出流(例如文件或标准输出)

以下是一个简单的示例,展示了如何使用 fflush() 和错误处理:

#include<stdio.h>
#include <errno.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    const char *text = "Hello, World!\n";
    fputs(text, file);

    // 刷新输出流
    if (fflush(file) != 0) {
        perror("Error flushing output stream");
        fclose(file);
        return 1;
    }

    printf("Successfully wrote to file and flushed the output stream.\n");

    fclose(file);
    return 0;
}

在这个示例中,我们首先打开一个名为 example.txt 的文件。然后,我们将一些文本写入文件,并尝试使用 fflush() 刷新输出流。如果 fflush() 返回非零值,表示发生了错误,我们可以使用 perror() 函数打印相应的错误消息。最后,我们关闭文件并退出程序。

0