Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Once Ive used freopen, how can I get the original stdout (or stdin) back?

original stdin stdout Used
0
Posted

Once Ive used freopen, how can I get the original stdout (or stdin) back?

0

There isn’t a good way. If you need to switch back, the best solution is not to have used freopen in the first place. Try using your own explicit output (or input) stream variable, which you can reassign at will, while leaving the original stdout (or stdin) undisturbed. For example, declare a global FILE *ofp; and replace all calls to printf( … ) with fprintf(ofp, … ). (Obviously, you’ll have to check for calls to putchar and puts, too.) Then you can set ofp to stdout or to anything else. You might wonder if you could skip freopen entirely, and do something like FILE *savestdout = stdout; stdout = fopen(file, “w”); /* WRONG */ leaving yourself able to restore stdout later by doing stdout = savestdout; /* WRONG */ but code like this is not likely to work, because stdout (and stdin and stderr) are typically constants which cannot be reassigned (which is why freopen exists in the first place). It may be possible, in a nonportable way, to save away information about a stream before cal

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123