redirect stdout/stderr to file under unix c++ - again

前端 未结 6 990
说谎
说谎 2021-02-15 15:51

What I want to do

redirect stdout and stderr to one or more files from inside c++

Why I need it

I am using an external, pr

6条回答
  •  渐次进展
    2021-02-15 16:09

    Are you looking for something like this :-

    int main()
    {
        // Save original std::cin, std::cout
        std::streambuf *coutbuf = std::cout.rdbuf();
        std::streambuf *cinbuf = std::cin.rdbuf(); 
    
        std::ofstream out("outfile.txt");
        std::ifstream in("infile.txt");
    
        //Read from infile.txt using std::cin
        std::cin.rdbuf(in.rdbuf());
    
        //Write to outfile.txt through std::cout 
        std::cout.rdbuf(out.rdbuf());   
    
        std::string test;
        std::cin >> test;           //from infile.txt
        std::cout << test << "  "; //to outfile.txt
    
        //Restore back.
        std::cin.rdbuf(cinbuf);   
        std::cout.rdbuf(coutbuf); 
    
    }
    

    From my earlier answer

提交回复
热议问题