Search code examples
c++filestdinfreopen

Redirecting output to file then back to console in C++


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.


Solution

  • Probably what you are looking for is rdbuf() as mentioned by doomista in the comments.

    Here is a way to redirect Output.

    #include <iostream>
    #include <fstream>
    
    int main()
    {
        /** backup cout buffer and redirect to out.txt **/
        std::ofstream out("out.txt");
    
        auto *coutbuf = std::cout.rdbuf();
        std::cout.rdbuf(out.rdbuf());
    
        std::cout << "This will be redirected to file out.txt" << std::endl;
    
        /** reset cout buffer **/
        std::cout.rdbuf(coutbuf);
    
        std::cout << "This will be printed on console" << std::endl;
    
        return 0;
    }