Snippets – redirecting stdin,stdout,stderr to a file


I'm starting a new category called snippets.  These posts will be little bits of code that I think are interesting or that I needed to do but took me a while to find or figure out.  I'm posting these because I want a place to collect them and maybe other folks can find them useful as well.

The first one is how to hook up stdout,stdin,stderr to files and then hook them back up to the console in C++.

FILE *fpin, *fpout, *fperr;
bool in_redirected, out_redirected, err_redirected;

inredirected = outredirected = errredirected = false;

if ((fpin = freopen("stdin.txt","rt",stdin)) != NULL)
   in_redirected = true;

if ((fpout = freopen("stout.txt","wt",stdout)) != NULL)
   out_redirected = true;

if ((fperr = freopen("stderr.txt","wt",stderr)) != NULL)
   err_redirected = true;

// do stuff with console redirected to files

if (in_redirected) freopen("CON","rt",stdin);
if (out_redirected) freopen("CON","wt",stdout);
if (err_redirected) freopen("CON","wt",stderr);

 

Skip to main content