user15161503
user15161503

Reputation:

How to set stdin and stdout to default state?

I have redirected stdin to file1.txt and stdout to file2.txt by freopen().

freopen("file1.txt","r",stdin);

freopen("file2.txt","w",stdout);

I have done some operations and now I want to take input from user through stdin and print the output through stdout only ( not through files ).

How can I do that?

Upvotes: 0

Views: 532

Answers (1)

Daniel Kleinstein
Daniel Kleinstein

Reputation: 5512

Before you call freopen, you need to duplicate stdout/stdin's file descriptors using dup, and restore them when you're done by using dup2.


For instance, for stdout:

#include <unistd.h>

...

int fd = dup(STDOUT_FILENO);
freopen("file1.txt", "w", stdout);

printf("Writing to file1\n");
fflush(stdout);

close(STDOUT_FILENO);
dup2(fd, STDOUT_FILENO);
printf("Writing to console\n");

Upvotes: 3

Related Questions