当前位置: C语言 -- 标准库 -- <stdio.h> -- fflush

fflush函数


概要:
#include <stdio.h>
int fflush(FILE *stream);

描述:

如果参数stream指向的流是输出流或者最近操作不是输入操作的更新流,该函数将流的任何未写入数据传递到宿主环境(host enviroment)以便写入文件;否则函数行为是未定义的。

如果参数stream是空指针,fflush函数会对所有上述流执行刷新操作。


参数:
FILE *stream

FILE类型指针,指向要刷新的流。


返回值:

如果发生写入错误(write error),函数为流设置错误指示符,并返回EOF;否则函数返回0


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
/*函数fflush范例*/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *pFile;
    int ch;

    /*创建文件。*/
    pFile = fopen("gch.txt", "w+");
    if(pFile == NULL)
    {
        perror("Fail to create the file");
        exit(EXIT_FAILURE);
    }
    
    fputs("The darkest hour is that before the dawn.", pFile);

    fflush(pFile);
    rewind(pFile);

    /*输出文件内容。*/
    while((ch=fgetc(pFile)) != EOF)
        putchar(ch);

    /*关闭文件。*/
    fclose(pFile);

    return 0;
}


结果:

创建一个名为gch.txt、内容为The darkest hour is that before the dawn.的文件,并输出文件内容。


相关内容:
fopen 打开文件的函数。
fclose 关闭文件的函数。
freopen 重新打开文件的函数。