[英]file descriptors, difference between printf and std::cout
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
//#include <iostream>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
int main(){
int stdout = dup(1);
char p[] = "test.txt";
close(1);
int output = open(p, O_WRONLY | O_CREAT | O_TRUNC, 0777);
//std::cout << "lala" << endl;
printf("lala\n");
close(output);
dup(stdout);
close(stdout);
printf("lolo\n");
// std::cout << "lolo" << endl;
return 0;
}
我認為printf和std :: cout必須輸出相同的內容,我想在文件上顯示“ lala”,並在終端屏幕上顯示“ lolo”,為什么這個版本(帶有prinf)在屏幕上打印所有內容,而在版本中顯示“ std :: cout“即可打印我喜歡的東西。
這與stdio
庫的內部緩沖有關。 "lala\\n"
太小,無法立即沖洗到流中,因此將其保留在printf
內部緩沖區中,直到以后沖洗為止。
如果添加一個fflush
則會得到所需的結果:
int main(){
int stdout_fd = dup(1);
char p[] = "test.txt";
close(1);
int output = open(p, O_WRONLY | O_CREAT | O_TRUNC, 0777);
//std::cout << "lala" << endl;
printf("lala\n");
fflush(stdout); // flush the internal buffer
close(output); // fclose would flush too
dup(stdout_fd);
close(stdout_fd);
printf("lolo\n");
// std::cout << "lolo" << endl;
return 0;
}
我還重命名了您的局部變量stdout
因為這是stdio
全局定義的變量。 stdin
和stderr
都是FILE *
指向這些對象的stdio控制流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.