Microsoft KB Archive/58667: Difference between revisions

From BetaArchive Wiki
(importing KB archive)
 
m (Text replacement - "<" to "<")
Line 84: Line 84:
<pre class="codesample">// Compile options needed: none
<pre class="codesample">// Compile options needed: none


#include &lt;stdio.h&gt;
#include <stdio.h&gt;
#include &lt;stdlib.h&gt;
#include <stdlib.h&gt;


void main(void)
void main(void)

Revision as of 09:26, 21 July 2020

Knowledge Base


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
    • Microsoft Visual C++ 4.0 Standard Edition
    • Microsoft Visual C++ 5.0 Standard Edition
    • Microsoft Visual C++ 6.0 Service Pack 5



This article was previously published under Q58667


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:

   freopen( "file.txt", "w", 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:

   freopen( "CON", "w", 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

#include <stdio.h>
#include <stdlib.h>

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

   printf("this is stdout output\n");

   stream = freopen("CON", "w", stdout);

   printf("And now back to the console once again\n");
}

This program assumes that stdout is to be redirected toward the console at the end of the program.

Keywords: kbhowto KB58667