![](/img/trans.png)
[英]Why won't this printf() statement print two string variables in C?
[英]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-err而不是hello-out。為什么會這樣?有人可以解釋它背后的原因嗎?
如果您在郵件中添加'\\n'
,它將(或應該),即。 "hello-out\\n"
原因是stdout
被緩沖以便更有效,而stderr
不緩沖它的輸出,更適合於錯誤消息和需要立即打印的東西。
stdout
通常會在以下情況下刷新 :
\\n
) stdin
讀入 fflush()
被調用 編輯:我想在計算機崩潰之前添加的另一件事...兩次......是你也可以使用setbuf(stdout, NULL);
禁用緩沖stdout
。 在我不得不使用write()
(Unix)並且不希望我的輸出被緩沖之前,我已經這樣做了。
它並不總是將輸出打印到stdout,因為設計stdout是BUFFERED輸出,而stderr是無緩沖的。 通常,對於緩沖輸出流,直到系統“自由”執行此操作才會轉儲流。 因此,在刷新之前,數據可以持續緩沖很長一段時間。 如果要強制緩沖區沖洗,可以使用fflush
手動執行此操作
#include<stdio.h>
#include <unistd.h>
int main(){
while(1)
{
fprintf(stdout,"hello-out");
fflush(stdout); /* force flush */
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
更新:當連接到終端時, stdout是行緩沖的,否則只是緩沖(例如重定向或管道)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.