I have below program,
void Print()
{
printf("\nCall from Print\n");
}
int main()
{
FILE * pFile;
char mystring [100];
pFile = freopen ("myfile.txt" , "r", stdin);
if (pFile == NULL)
{
perror ("Error opening file");
}
else
{
if ( fgets (mystring , 100 , pFile) != NULL )
{
freopen("myfile.txt" , "a", stdout);
Print();
printf("Here it is\n");
//puts (mystring);
}
fclose(stdout);
fclose (pFile);
}
printf("Hello World\n");
return 0;
}
Now when I am execting the program I can not see the output in console window. All the outputs are redirected into myfile.txt
file. I want the output should come in both console
and myfile.txt
too.
After all that why printf("Hello World\\n")
is not getting printed in console. How to make it printed in console also?
My am working in windows-7, visual studio-2010
The easiest way would be to be more explicit about it, by manually printing to both stdout
(the original, to get output to the console) and to your file.
By re-opening stdout
to point at the file, you remove the connection to the console window, which is why no output appears.
You could also only use stdout
, and use an external tool such as tee
to duplicate the output into a file.
the
freopen("myfile.txt" , "a", stdout);
will make your stdout
output to the file myfile.txt
This function will redirect the output from console to the file myfile.txt
Even if you use fclose(stdout);
, this will not back the output of stdout to the console it will only close the myfile.txt
refer to the following link for more details Strange behaviour when redirecting stdout in C
in order to get the output in both the console and in the file, You have tokeep the stdout untouch do not reopen it with freaopen()
and do not close it. and You have to print your message twice in the file and in the stdout
I have also faced such requirements once.
I have made one macro for such printing log. That print macro expands in one function which print that message in my log file and stdout or stderr depending upon some control variable setting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.