Strange behaviour when redirecting stdout in C

469 views Asked by At

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.

1

There are 1 answers

0
Daniel Fischer On BEST ANSWER

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.