Tuesday, 3 April 2012

The freopen Functions in C & C++

The freopen Function.

The freopen function in the C Standard I/O library <cstdio> is a useful to redirect output destined for the stdout to a text file. I discussed how to use the fprintf function to send output to either a text file or the stdout. See here. The same result is achieved here using the printf and freopen functions.

Method 1.

freopen(Filename, "w", stdout);

There is no return value to indicate if the file was opened or if there was an error.

Method 2.

iReturn = freopen(Filename, "w", stdout);

On failure, a null pointer is returned otherwise the return value is a pointer to the file. Beyond testing for an error, this return value is used to close the file.


While my example uses the stdout, the freopen function can be used with the stdin and stderr objects.

Test Code.

I tested the functions in Visual C++ 2010 as an console application.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

int main()
     // Redirect stdout to a file.

     // Declare pointer to the file.
     FILE* pFileHandle;
     char Filename[] = "MyFile.txt";

     // Returns null is the open failed.
     pFileHandle = freopen(Filename, "w", stdout);
     printf("pFileHandle is %X.\n\n", pFileHandle);

     // Header.
     printf("Using freopen in C & C++\n\n");

     // Some use of printf.
     printf("Sending the printf output to a file instead of the stdout.\n");
     printf("The freopen function allows for this redirection.\n\n");

     // Use variable for a string.
     char * Text = "A text string only from a variable.\n\n";
     printf("%s", Text);

     // Int type.
     int Salary = 375000;
     int Bonus = -35000;
     printf("Salary is: %8d.\n", Salary);
     printf("Bonus  is: %8d.\n", Bonus);

     // Close the file.

     // Keep console window open.

     // Return some value.
     return 0;
} // end main


No comments:

Post a Comment