Microsoft KB Archive/58667

= How to redirect stdout to a file from a Visual C/C++ program =

Article ID: 58667

Article Last Modified on 4/28/2005

-

APPLIES TO

 The C Run-Time (CRT), when used with:  Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul>

 Microsoft Visual C++ 5.0 Standard Edition</li></ul>

 Microsoft Visual C++ 6.0 Service Pack 5</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q58667

<div class="notice_section">

<div class="summary_section">

SUMMARY
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: <pre class="fixed_text">  freopen( &quot;file.txt&quot;, &quot;w&quot;, stdout ); This statement causes all subsequent output, which is typically directed towards stdout, to go to the file FILE.TXT.

To return stdout to the display (the default stdout), use the following call: <pre class="fixed_text">  freopen( &quot;CON&quot;, &quot;w&quot;, stdout ); In both of these cases, check the return value of freopen to make sure that the redirection actually took place.

Below is a short program to demonstrate the redirection of stdout:

Sample Code
// Compile options needed: none


 * 1) include <stdio.h>
 * 2) include <stdlib.h>

void main(void) {  FILE *stream ; if((stream = freopen(&quot;file.txt&quot;, &quot;w&quot;, stdout)) == NULL) exit(-1);

printf(&quot;this is stdout output\n&quot;);

stream = freopen(&quot;CON&quot;, &quot;w&quot;, stdout);

printf(&quot;And now back to the console once again\n&quot;); } This program assumes that stdout is to be redirected toward the console at the end of the program.

Keywords: kbhowto KB58667

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.