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?
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.
@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