谷动谷力

 找回密码
 立即注册
查看: 391|回复: 0
打印 上一主题 下一主题
收起左侧

【C语言】fflush()函数浅析

[复制链接]
跳转到指定楼层
楼主
发表于 2023-12-12 09:56:56 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
【C语言】fflush()函数浅析


fflush()函数:更新缓存区。

头文件:#include<stdio.h>
函数定义:int fflush(FILE *stream);
函数说明:调用fflush()会将缓冲区中的内容写到stream所指的文件中去.若stream为NULL,则会将所有打开的文件进行数据更新。

fflush(stdin):刷新缓冲区,将缓冲区内的数据清空并丢弃。
fflush(stdout):刷新缓冲区,将缓冲区内的数据输出到设备。
看如下代码:
  1. #inlcude<stdio.h>

  2. int main()
  3. {
  4.     printf("hello");
  5.     sleep(5);

  6.     printf(" world!\n");

  7.     return 0;
  8. }

  9. //先进入sleep后打印hello world!
复制代码


  1. #include<stdio.h>

  2. int main()
  3. {
  4.     printf("hello");

  5.     fflush(stdout);//将缓冲区的内容输出到设备中
  6.     sleep(5);

  7.     printf(" world!\n");

  8.     return 0;
  9. }

  10. //先打印hello 在进入sleep 后打印world!
复制代码


fflush()的作用是用来刷新缓冲区,fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃; fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西强制打印到标准输出设备上。

fflush(stdin)不太常用,在有些编译器中是错误的用法,可以用以下方法替代:while(getchar()!='/n');

fflush(stdout)在单进程程序中作用不大,但在多进程程序中很有用。程序的输出内容一般不会立即输出,而是在程序结束后再输出。fflush(stdout)会强制每次printf()都立即显示在标准输出设备上。
  1. #include<stdio.h>

  2. #include<unistd.h>

  3. int main()
  4. {
  5.     printf("hello");

  6.     //fflush(stdout);

  7.     fork();

  8.     return 0;
  9. }
复制代码


第一种没 \n ,在fork之前hello还在缓冲区,所以父子进程均要输出hello;
第二种有 \n ,即 printf(“hello\n”); 由于printf打印到标准输出时,终端是行缓存, 遇到\n就将缓存输出,所以 fork之前缓存无内容,只打印一次;
stdout默认是是行缓冲的,遇到 \n 就写内容清缓存。

而加上fflush(stdout); 与 有 \n 作用一样,只是不换行。

+10
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|深圳市光明谷科技有限公司|光明谷商城|Sunshine Silicon Corpporation ( 粤ICP备14060730号|Sitemap

GMT+8, 2024-4-28 16:42 , Processed in 0.103974 second(s), 39 queries .

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表