Linux中fflush的錯(cuò)誤處理方式

小樊
82
2024-08-28 21:13:17

在 Linux 系統(tǒng)中,fflush() 函數(shù)用于刷新輸出流(例如文件或標(biāo)準(zhǔn)輸出)

以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用 fflush() 和錯(cuò)誤處理:

#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;
}

在這個(gè)示例中,我們首先打開(kāi)一個(gè)名為 example.txt 的文件。然后,我們將一些文本寫(xiě)入文件,并嘗試使用 fflush() 刷新輸出流。如果 fflush() 返回非零值,表示發(fā)生了錯(cuò)誤,我們可以使用 perror() 函數(shù)打印相應(yīng)的錯(cuò)誤消息。最后,我們關(guān)閉文件并退出程序。

0