Select the product you need help with
- Internet Explorer
- Windows Phone
- More products
How to redirect stdout to a file from a Visual C/C++ program
Article ID: 58667 - View products that this article applies to.
This article was previously published under Q58667
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: April 28, 2005 - Revision: 4.0