为什么 printf 在调用后不会刷新,除非格式字符串中有换行符? [英] Why does printf not flush after the call unless a newline is in the format string?

查看:21
本文介绍了为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么printf 不会在调用后刷新,除非格式字符串中有换行符?这是 POSIX 行为吗?我怎样才能让 printf 每次都立即刷新?

Why does printf not flush after the call unless a newline is in the format string? Is this POSIX behavior? How might I have printf immediately flush every time?

推荐答案

stdout 流在默认情况下是行缓冲的,因此只会在到达换行符后(或告诉).您有几个选项可以立即打印:

The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

  • Print to stderrinstead using fprintf (stderr is unbuffered by default):

fprintf(stderr, "I will be printed immediately");

  • 在需要时使用 fflush 刷新 stdout:

    printf("Buffered, will be flushed");
    fflush(stdout); // Will now print everything in the stdout buffer
    

  • 使用 setbuf 在标准输出上禁用缓冲:

  • Disable buffering on stdout by using setbuf:

    setbuf(stdout, NULL);
    

  • 或者使用更灵活的setvbuf:

    setvbuf(stdout, NULL, _IONBF, 0); 
    

  • 这篇关于为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆