How do I 'restore' my output (stdout) back to the terminal after redirecting it to a file. I want to be able to output to a file for a specific section of code, then close that file and put output back to the screen/terminal.

fprintf(stdout, "This will go to the terminal.\n");
stdout = fopen("/tmp/somefile.txt", "w");
fprintf(stdout, "This will go to the file /tmp/somefile.txt.\n");
...
fclose(stdout);
fprintf(stdout, "I WANT this to go to the terminal.\n");

Using this code, I get nothing after the close (obviously closing is wrong). How do I restore the output?

I should have specified that I am running in Linux and not windows.

So according to this page you gave, something like:

fprintf(stdout, "This will go to the terminal.\n");

FILE *myOutput;
myOutput = fopen("/tmp/somefile.txt", "w");
fprintf(myOutput, "This will go to the file /tmp/somefile.txt.\n");
...
fclose(myOutput);
fprintf(stdout, "I WANT this to go to the terminal.\n");

Yes, that should work as you expect it to.

This is easier if all your code is contained in one file, but what about multi-threaded programs - I will then have to pass this to every function, right?

According to the post, this is how its done (for anyone interested):

fprintf(stdout, "This will go to the terminal.\n");

//Save position of current standard output
fpos_t pos;
fgetpos(stdout, &pos);
int fd = dup(fileno(stdout));
freopen("/tmp/somefile.txt", "w", stdout);

fprintf(stdout, "This will go to the file /tmp/somefile.txt.\n");

//Flush stdout so any buffered messages are delivered
fflush(stdout);
//Close file and restore standard output to stdout - which should be the terminal
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);

fprintf(stdout, "This will go to the terminal.\n");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.