You are here:

C/freopen

Advertisement


Question
-------------------------
Followup To
Question -
I write simple console functions and use freopen to redirect printf statements to a file. Can the output to the file be "turned off" and the printf outputs redirected back to the console window later in the code?
Answer -
Yes. Change your file pointer back to STDOUT.

-ssnkumar
Thanks but I tried various ways to ressign with no luck.
freopen("test.txt", "w", stdout);
then freopen(stdout, "w", "test.txt"); //wont compile.
   then I tried
temp = freopen("test.txt", "w", stdout);
then temp = stdout; // did not work.
Not sure how to reassign STDOUT.
Rudy

Answer
Here is a sample program I have written to demonstrate how it works. Compile and run it.
Hope it helps....

-ssnkumar

#include<stdio.h>

main()
{
       FILE *fp = freopen("file.txt", "w", stdout);

       printf("Hello\n");

       fclose(fp);

       stdout = fdopen(2, "w");
       printf("OVER!!\n");
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.