Microsoft KB Archive/58667

From BetaArchive Wiki
< Microsoft KB Archive
Revision as of 16:57, 18 July 2020 by 3155ffGd (talk | contribs) (importing KB archive)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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