fclose & fopen VS freopen

May 24, 2011 at 12:40pm
freopen is supposed to close a file and open another right?
then why not use fclose followed by an fopen
I tried this appraoch with a normal file and it worked
but by using this with stdout it didn't work i had to use freopen
why is that?

The first one was

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

int main(void)
{
FILE * fp = fopen("example.txt", "w");
fprintf(fp, "this is the first time\n");
fclose(fp);
fp = fopen("example2.txt", "w");
fprintf(fp, "this is the second time\n");
fclose(fp);
return 0;
}

this is the second one with stdout that didn't work (didn't write anything to the example.txt)

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

int main(void)
{
fclose(stdout);
if (! (stdout = fopen("example.txt", "w"))) perror("Failed");;
printf("hey\n");
return 0;
}


BUT IN THE LAST EXAMPLE IF I CHANGE printf("hey\n"); to fprintf(stdout, "hey\n"); it works and printf is supposed to print to the stdout why does this happen?
Last edited on May 25, 2011 at 3:03pm
May 24, 2011 at 3:06pm
What error did you see?
May 24, 2011 at 3:10pm
man pages wrote:
Since the symbols stdin, stdout, and stderr are specified to be macros, assigning to them is non-portable.
The standard streams can be made to refer to different files with help of the library function freopen(3), specially introduced to make it possible to reassign stdin, stdout, and stderr.
May 24, 2011 at 7:20pm
@kooth it doesn't give an error it just doesn't write anything in the file "example.txt"

@ne555 that makes me think of another question. What is that macro exactly? I tried to open the stdio.h file and didn't find an exact description of what it is? i'm just wondering
May 25, 2011 at 8:56am
freopen is supposed to close a file and open another right?
Wrong. The effect of freopen is to reassign a handle to another source.

In your example (that works) fp is reassinged from writing to example.txt to example2.txt
May 25, 2011 at 12:04pm
I"M SORRY I had put another example for example one than the one I meant to post I have changed it and written another note in the end
Last edited on May 25, 2011 at 12:04pm
Topic archived. No new replies allowed.