The task is to read input from input.txt
and write the output to output.txt
.
However on completion of the above tasks, further instructions/output should now be displayed to the console.
Came to know about freopen() in c++ which works fine for the first half of the given task. But unfortunately, I have no idea how to redirect the output back to the console again.
void writeIntoFile(){
freopen("input.txt","r",stdin); // Task 1. Reading from input.txt file
freopen("output.txt","w",stdout); // Task 2. Writing to output.txt file
printf("This sentence is redirected to a file.");
fclose(stdout);
printf("This sentence is redirected to console"); // Task 3. Write further output to console
}
What I expected from fclose() was that it would end up writing into the text file and would hence further write the output into the console, but it doesn't. How can I achieve task 3 as well.
Probably what you are looking for is rdbuf() as mentioned by doomista in the comments.
Here is a way to redirect Output.