簡體   English   中英

文件描述符,printf和std :: cout之間的區別

[英]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全局定義的變量。 stdinstderr都是FILE *指向這些對象的stdio控制流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM