Article ID: 58667
This article explains how to redirect stdout to a file from a C program, then restore the original stdout at a later point in the same program. The C function typically used to redirect stdout or stdin is freopen(). To redirect stdout to a file called FILE.TXT, use the following call:
This statement causes all subsequent output, which is typically directed towards stdout, to go to the file FILE.TXT.
freopen( "file.txt", "w", stdout );
To return stdout to the display (the default stdout), use the following call:
In both of these cases, check the return value of freopen() to make sure that the redirection actually took place.
freopen( "CON", "w", stdout );
Below is a short program to demonstrate the redirection of stdout:
This program assumes that stdout is to be redirected toward the console at the end of the program.
Article ID: 58667 - Last Review: June 17, 2014 - Revision: 5.0