fflush

排清資料流。

語法

int fflush(
   FILE *stream
);

參數

stream
FILE 結構的指標。

傳回值

如已成功排清緩衝區,fflush 會傳回 0。 如果指定的資料流沒有任何緩衝區或僅開啟為唯讀,也會傳回值 0。 傳回 EOF 值表示錯誤。

注意

如果 fflush 傳回 EOF,表示資料可能是因為寫入失敗而遺失。 設定重大錯誤處理常式時,最安全的做法是以 setvbuf 函式關閉緩衝,或使用低階 I/O 常式,例如_open_close_write,而不是資料流 I/O 函式。

備註

fflush 函式會排清資料流 stream。 如果資料流程是以寫入模式開啟,或是在更新模式中開啟,而最後一個作業是寫入, fflush 請將資料流程緩衝區的內容寫入基礎檔案或裝置,並捨棄緩衝區。 如果資料流在讀取模式中開啟,或如果資料流沒有緩衝區,則呼叫 fflush 不起作用,保留所有的緩衝區。 呼叫 fflush 會取消任何之前針對資料流呼叫 ungetc 的效果。 資料流在呼叫之後仍保持開啟。

如果 streamNULL,則行為與在每個開啟的資料流中呼叫 fflush 一樣。 所有在寫入模式中開啟的資料流,以及所有在更新模式中開啟且最後作業是寫入的資料流,都會排清。 呼叫對其他資料流不起作用。

緩衝區通常是由作業系統維護,這會決定資料自動寫入磁碟的最佳時機︰當緩衝區已滿、當資料流已關閉,或當程式正常結束但不關閉資料流。 執行階段程式庫的認可到磁碟功能可讓您確保將重大資料直接寫入至磁碟,而不是作業系統緩衝區。 若未重寫現有的程式,您可以將程式的物件檔連結至 COMMODE.OBJ ,以啟用此功能。 在產生的可執行檔中,_flushall 呼叫會將所有緩衝區的內容寫入至磁碟。 只有 _flushallfflush 會受到 COMMODE.OBJ 影響。

如需控制認可到磁片功能的資訊,請參閱 串流 I/O fopen_fdopen

此函示鎖定呼叫執行緒,所以是安全執行緒。 如需非鎖定版本,請參閱 _fflush_nolock

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

函式 必要的標頭
fflush <stdio.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_fflush.c
// Compile with: cl /W4 crt_fflush.c
// This sample gets a number from the user, then writes it to a file.
// It ensures the write isn't lost on crash by calling fflush.
#include <stdio.h>

int * crash_the_program = 0;

int main(void)
{
    FILE * my_file;
    errno_t err = fopen_s(&my_file, "myfile.txt", "w");
    if (my_file && !err)
    {
        printf("Write a number: ");

        int my_number = 0;
        scanf_s("%d", &my_number);

        fprintf(my_file, "User selected %d\n", my_number);

        // Write data to a file immediately instead of buffering.
        fflush(my_file);

        if (my_number == 5)
        {
            // Without using fflush, no data was written to the file
            // prior to the crash, so the data is lost.
            *crash_the_program = 5;
        }

        // Normally, fflush is not needed as closing the file will write the buffer.
        // Note that files are automatically closed and flushed during normal termination.
        fclose(my_file);
    }
    return 0;
}
5
User selected 5

另請參閱

資料流 I/O
fclose, _fcloseall
_flushall
setvbuf