为什么 printf 在调用后不会刷新,除非格式字符串中有换行符? [英] Why does printf not flush after the call unless a newline is in the format string?
问题描述
为什么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:
打印到
stderr
而不是使用fprintf
(stderr
是 默认无缓冲):
Print to
stderr
instead usingfprintf
(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屋!