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.