16 - fflush()函数

本文详细介绍了fflush()函数的用途、参数及返回值等信息,并通过示例代码展示了如何使用fflush()函数刷新输出缓冲区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
  1. fflush()函数主要用于刷新输出缓冲区,即显示地将缓冲区中的数据写入文件;
  2. fflush()函数不适用于清空输入缓冲区,早期的Visual Studio版本支持使用fflush(stdin)来清空标准输入流stdin的缓冲区,但从VS2015版本开始,fflush(stdin)在Visual Studio中已不再支持;
  3. fclose()函数关闭文件或者程序终止关闭文件时,与该文件关联的所有缓冲区都会自动被刷新或清空;这意味着,即使你没有显式调用fflush()函数,输出缓冲区中的数据也会被写入到文件中;但是,在程序崩溃或异常终止的情况下,自动刷新可能无法发生;因此,在关键数据需要被写入文件时,必须显式调用fflush()函数来刷新输出缓冲区。

2 参数

fflush()函数只有一个参数stream:

  1. 参数stream是fflush()函数要刷新的流,类型为FILE*;stream可以是文件流或标准输出流;当是文件流时,stream就是fopen()函数的返回值;当是标准输出流时,stream就是stdout。

cstdio库描述如下:

stream
1. Pointer to a FILE object that specifies a buffered stream.

3 返回值

fflush()函数的返回值类型为int型:

  1. 刷新成功,返回0;
  2. 刷新失败,返回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;
}

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. 以"r+"模式打开文件;
  2. 向文件写入字符串"hello world";
  3. 刷新文件流;
  4. 重定位文件,使文件位置指示符指向文件开始;
  5. 读文件并打印。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值