Question

I'm trying to redirect stdout to a file and then restore it back to original in C, but I'm facing the following strange issue - the following piece of code succesfully writes
in stdout
in stdout
in stdout and in file in the respective file which is all OK.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    printf("in stdout \n");
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

However, removing the first row of my main function:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

leads to in file
in stdout
being written on stdout and nothing being written in the file. I wonder how this happened? Thanks for any help.

Was it helpful?

Solution

It's a buffering issue. The buffer you write "in file" to isn't flushed before stdout is reinstalled, so the output goes to stdout and not to the file. Adding fflush(stdout); fixed it here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top