【C语言】关于printf的缓冲区问题

2023-05-16

前言

使用printf时,发现要打印的东西并没有打印出来,而是要等到下次printf(“\n”)或者程序退出时才会一起打印出来。
代码示例:

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

int main()
{
        printf("hello world");
        sleep(5);
        printf("\n");
        printf("hello world again");
        sleep(5);
        exit(0);
}

运行结果:hello world并不是立刻打印出来,而是等第一个5s阻塞结束才打印出来;同样的,hello world again也是等到程序退出时才打印出来。


一、原因

printf是有缓冲区的,并不是直接将内容输出到屏幕上,它会先将需要输出的内容放入到缓冲区,直到缓冲区满或者遇到"\n"或者程序结束才将内容输出的屏幕上。

二、解决方法

1.关闭缓冲区:setbuf(stdout,NULL)

代码如下(示例):

#include <stdio.h>

int main(void)
{
    int i=0;
 
    setbuf(stdout,NULL);	// 关闭缓冲区
    for(i=0; i<10; i++)
    {
       printf("hello world");
       sleep(1);
    }
    return 0;
}

运行结果:hello world

2.刷新缓冲区:fflush(stdout)

代码如下(示例):

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
        printf("hello world");
        fflush(stdout);		//刷新缓冲区
        sleep(1);
        exit(0);
}

运行结果:hello world


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【C语言】关于printf的缓冲区问题 的相关文章

随机推荐