为什么不这样C程序打印第一printf语句? [英] why doesn't this c programme print the first printf statement?
问题描述
#include<stdio.h>
#include <unistd.h>
int main(){
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
在编写这个程序gcc和执行上只打印Hello-犯错,不打招呼,out.Why是这样的吗?有人可以请解释其背后的原因是什么?
On compiling this programme in gcc and on executing it only prints hello-err and not hello-out.Why is that so?Can someone please explain the reason behind it?
推荐答案
如果您在的'\\ n'
添加到您的消息这将(或应该),即得。 喂出\\ n
。
If you add a '\n'
to your message it will (or should), ie. "hello-out\n"
.
的原因是,标准输出
终止的缓存的,以便更有效,而标准错误
不缓冲它的输出,更适合那些需要立即打印错误消息和事情。
The reason being is that stdout
is buffered in order to be more efficient, whereas stderr
doesn't buffer it's output and is more appropriate for error messages and things that need to be printed immediately.
标准输出
将一般的是刷新的时候:
- 换行符(
\\ n
)将被打印 - 您从读
标准输入
-
fflush()
上调用它
- A newline (
\n
) is to be printed - You read in from
stdin
fflush()
is called on it
编辑:我想添加在我的电脑死机两次...其他的事情......是,你还可以使用则setbuf(标准输出,NULL);
禁用标准输出
。我过去就这么做过,当我不得不使用的write()
(UNIX),不想我的输出进行缓冲。
The other thing I wanted to add before my computer crashed...twice...was that you can also use setbuf(stdout, NULL);
to disable buffering of stdout
. I've done that before when I've had to use write()
(Unix) and didn't want my output to be buffered.
这篇关于为什么不这样C程序打印第一printf语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!