简体   繁体   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;
}

I think that printf and std::cout have to output the same thing, I want "lala" on the file, and "lolo" on the terminal screen, why this version (with prinf) print everything on screen and the version with "std::cout" print the things as I like. 我认为printf和std :: cout必须输出相同的内容,我想在文件上显示“ lala”,并在终端屏幕上显示“ lolo”,为什么这个版本(带有prinf)在屏幕上打印所有内容,而在版本中显示“ std :: cout“即可打印我喜欢的东西。

This has to do with the internal buffering of the stdio library. 这与stdio库的内部缓冲有关。 "lala\\n" is too small to be flushed to the stream straight away, so it is kept in printf internal buffer until it is flushed later. "lala\\n"太小,无法立即冲洗到流中,因此将其保留在printf内部缓冲区中,直到以后冲洗为止。

If you add an fflush then you get the desired result: 如果添加一个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;
}

Also I have renamed your local variable stdout because that is a globally defined one by stdio . 我还重命名了您的局部变量stdout因为这是stdio全局定义的变量。 Also stdin and stderr are FILE * pointing to the stdio control streams for those. stdinstderr都是FILE *指向这些对象的stdio控制流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM