How to redirect std::cout / printf to file? (C++)

Manda Rajo 141 Reputation points
2022-05-30T15:01:52.48+00:00

Hi, I use Visual Studio 2015, and the code below doesn't work because the file "file.txt" is created but it's always empty.

   #include <conio.h>  
     
   #include <fstream>   
   #include <iostream>   
      
   int main() {  
       std::string outputFileName = "D:/file.txt";  
       bool printToFile = true;  
     
       std::streambuf *cout_oldBuf = nullptr;  
       if (printToFile) {  
           // Referenced from:  
           //     https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files  
           //     https://www.quora.com/How-do-I-output-all-my-cout-s-to-a-text-file-in-C  
           std::ofstream out(outputFileName.c_str());  
           cout_oldBuf = std::cout.rdbuf(); // Save old buf  
           std::cout.rdbuf(out.rdbuf()); // Redirect std::cout to the file.  
       }  
     
       std::cout << "Hello World\n";  
     
       if (printToFile) {  
           std::cout.rdbuf(cout_oldBuf);  
       }  
     
       std::cout << "Write on screen\n";  
     
       _getch();  
   }  

If it's impossible to solve the previous method then this is another method but it has an error, but note that this method can write to the file with success if the application/console is ran to the end, but not using break points:

   #include <conio.h>  
     
   #include <fstream>   
   #include <iostream>   
     
   int main()   
   {   
       // Referenced from:  
       //     https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files  
       //     https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-s-wfreopen-s?view=msvc-170  
     
       FILE *stream;  
     
       errno_t err;  
       err = freopen_s(&stream, "D:/file.txt", "w", stdout);  
       if (err != 0) {  
           // TODO  
       }  
     
       std::cout << "Hello world!\n";   
      
       // Error on the line stdout = ...: expression must be a modifiable lvalue  
       fclose(stdout);  
       stdout = fdopen(1, "w"); //reopen: 1 is file descriptor of std output  
      
       _getch();  
   }  
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,851 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 47,031 Reputation points
    2022-05-30T22:34:44.93+00:00

    Your output file is empty because it is closed before you try to write to it.

    Move the declaration of the std::ofstream object out OUTSIDE of the code block following the if statement that tests printToFile.

        std::ofstream out(outputFileName.c_str());
        if (printToFile) {
            // Referenced from:
            //     https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files
            //     https://www.quora.com/How-do-I-output-all-my-cout-s-to-a-text-file-in-C
            cout_oldBuf = std::cout.rdbuf(); // Save old buf
            std::cout.rdbuf(out.rdbuf()); // Redirect std::cout to the file.
        }
        
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. yu shang 1 Reputation point
    2022-12-30T08:37:13.313+00:00

    this solution is really cool. I have the similar use case: choose the output destination between console and a file.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.