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

9 篇文章 1 订阅

前言

使用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


  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用数组来实现环形缓冲区。下面是一个简单的示例代码: ```c #define BUFFER_SIZE 10 typedef struct { int buffer[BUFFER_SIZE]; int head; // 缓冲区头部索引 int tail; // 缓冲区尾部索引 } CircularBuffer; // 初始化环形缓冲区 void initCircularBuffer(CircularBuffer* cb) { cb->head = 0; cb->tail = 0; } // 向环形缓冲区中写入数据 void writeCircularBuffer(CircularBuffer* cb, int data) { cb->buffer[cb->tail] = data; cb->tail = (cb->tail + 1) % BUFFER_SIZE; } // 从环形缓冲区中读取数据 int readCircularBuffer(CircularBuffer* cb) { int data = cb->buffer[cb->head]; cb->head = (cb->head + 1) % BUFFER_SIZE; return data; } ``` 使用示例: ```c int main() { CircularBuffer cb; initCircularBuffer(&cb); writeCircularBuffer(&cb, 10); writeCircularBuffer(&cb, 20); writeCircularBuffer(&cb, 30); int data1 = readCircularBuffer(&cb); int data2 = readCircularBuffer(&cb); printf("%d\n", data1); // 输出: 10 printf("%d\n", data2); // 输出: 20 return 0; } ``` 这个示例中,我们使用数组 `buffer` 来存储数据,使用 `head` 和 `tail` 分别表示缓冲区的头部和尾部索引。在写入数据时,将数据存储在 `tail` 所指向的位置,并将 `tail` 的索引递增一位。在读取数据时,从 `head` 所指向的位置读取数据,并将 `head` 的索引递增一位。当 `tail` 或 `head` 达到缓冲区的末尾时,我们使用取余运算将其重新定位到缓冲区的开头,实现了循环利用缓冲区的效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值