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 会将所有缓冲区的内容写入磁盘中。 仅 _flushallfflushCOMMODE.OBJ 的影响。

有关控制提交到磁盘功能的信息,请参阅流 I/Ofopen_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