简体   繁体   中英

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.

This has to do with the internal buffering of the stdio library. "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.

If you add an fflush then you get the desired result:

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 . Also stdin and stderr are FILE * pointing to the stdio control streams for those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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