I want to write the contents of the console to a text file. That's why first I wrote a program for this purpose, but the program just hung (didn't stop) and I couldn't even open the file to see the results.
The following is my code:
#include<stdio.h>
int main()
{
// Print some lines on the output
printf("Hello, world.\n");
printf("My name\'s Amir Mohsen Ghasemi.\n");
printf("I\'m 13 years old.\n");
// Open a file in writing mode
FILE *fp = fopen("Result.txt", "w");
// Reset the file pointer of stdout to the beginning
rewind(stdout);
// Read a character from stdout and print it on fp
while(!feof(stdout))
putc(getc(stdout), fp);
fclose(fp);
return 0;
}
Then I searched on the web but most websites were talking about how to print contents of a file to the console. However, I found this question and then I used the freopen
function like this:
#include<stdio.h>
int main()
{
printf("Hello, world.\n");
printf("My name\'s Amir Mohsen Ghasemi.\n");
printf("I\'m 13 years old.\n");
FILE *file = freopen("Result.txt", "r+", stdout);
fclose(file);
return 0;
}
but the program above couldn't give me what I expected and a file with 233.3 MB is generated and I wasn't even able to open it.
So, what's the problem and how can I exactly deal with it?