缓冲数据是计算机物理内存中存储的临时数据或特定于应用程序的数据,直到某个时间点。
fflush() 函数定义在 <a href="/cpp-programming/library-function/cstdio" title="cstdio Header File"><cstdio></a> 头文件中。
fflush() 原型
int fflush(FILE* stream);
如果 stream 是一个输出流或更新流,并且其最后一个操作是输出,则调用 fflush() 函数会将任何缓冲的未写入数据写入关联的输出设备。
如果 stream 是一个空指针,则会刷新所有打开的输出流。
对于输入流和最后一个操作是输入的更新流,其行为是未定义的。
fflush() 参数
- stream: 要刷新的流。
fflush() 返回值
fflush() 函数返回
- 成功时返回零。
- 失败时返回 EOF,并设置文件流的错误指示符。
示例:fflush() 函数如何工作?
#include <cstdio>
#include <cstring>
int main()
{
int x;
char buffer[1024];
setvbuf(stdout, buffer, _IOFBF, 1024);
printf("Enter an integer - ");
fflush(stdout);
scanf("%d",&x);
printf("You entered %d", x);
return(0);
}
运行程序后,输出将是
Enter an integer - 2 You entered 2
在上面的程序中,尝试删除 `fflush(stdout)` 这一行并运行程序,以查看 fflush 的效果。字符串“Enter an integer - ”不会被写入屏幕,除非它被刷新。