1 函数原型
fflush():刷新指定流stream,函数原型如下:
int fflush ( FILE * stream );
cstdio库描述如下:
Flush stream
1. If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.
2. If stream is a null pointer, all such streams are flushed.
3. In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).
4. The stream remains open after this call.
5. When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.
- fflush()函数主要用于刷新输出缓冲区,即显示地将缓冲区中的数据写入文件;
- fflush()函数不适用于清空输入缓冲区,早期的Visual Studio版本支持使用fflush(stdin)来清空标准输入流stdin的缓冲区,但从VS2015版本开始,fflush(stdin)在Visual Studio中已不再支持;
- fclose()函数关闭文件或者程序终止关闭文件时,与该文件关联的所有缓冲区都会自动被刷新或清空;这意味着,即使你没有显式调用fflush()函数,输出缓冲区中的数据也会被写入到文件中;但是,在程序崩溃或异常终止的情况下,自动刷新可能无法发生;因此,在关键数据需要被写入文件时,必须显式调用fflush()函数来刷新输出缓冲区。
2 参数
fflush()函数只有一个参数stream:
- 参数stream是fflush()函数要刷新的流,类型为FILE*;stream可以是文件流或标准输出流;当是文件流时,stream就是fopen()函数的返回值;当是标准输出流时,stream就是stdout。
cstdio库描述如下:
stream
1. Pointer to a FILE object that specifies a buffered stream.
3 返回值
fflush()函数的返回值类型为int型:
- 刷新成功,返回0;
- 刷新失败,返回EOF。
C语言标准描述如下:
1. A zero value indicates success.
2. If an error occurs, EOF is returned and the error indicator is set (see ferror).
4 示例
示例代码如下所示:
int main()
{
//
char mybuffer[80] = { 0 };
FILE* pFile = NULL;;
// 打开文件
pFile = fopen("1.txt", "r+");
// 检查打开结果
if (pFile == NULL)
{
perror("Failed to open file ");
exit(1);
}
else
{
// 写文件
fputs("hello world", pFile);
// 刷新文件
fflush(pFile);
// 重定位文件
rewind(pFile);
// 读文件
fgets(mybuffer, 80, pFile);
// 打印
puts(mybuffer);
// 关闭文件
fclose(pFile);
}
//
return 0;
}
代码运行结果如下图所示:
代码及运行结果分析如下:
- 以"r+"模式打开文件;
- 向文件写入字符串"hello world";
- 刷新文件流;
- 重定位文件,使文件位置指示符指向文件开始;
- 读文件并打印。