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

前端 未结 6 993
说谎
说谎 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:06

    I was inspired by @POW and @James Kanze 's answers and put together a little RAII class for redirecting std::cout to a file. It is intended to demonstrate the principle.

    Code:

    #include 
    #include 
    #include 
    
    // RAII for redirection
    class Redirect {
        public:
        
        explicit Redirect(const std::string& filenm):
            _coutbuf{ std::cout.rdbuf() },   // save original rdbuf
            _outf{ filenm }
        {
            // replace cout's rdbuf with the file's rdbuf
            std::cout.rdbuf(_outf.rdbuf());
        }
        
        ~Redirect() {
            // restore cout's rdbuf to the original
            std::cout << std::flush;
            _outf.close();    ///< not really necessary
            std::cout.rdbuf(_coutbuf); 
        }
        
        private:
        
        std::streambuf* _coutbuf;
        std::ofstream _outf;
    };
    
    // == MAIN ==
    
    int main(int argc, char* argv[]) {
        std::cout << "This message is printed to the screen" << std::endl;
        {
            // scope for the redirection
            Redirect redirect{ "output.txt" };
            std::cout << "This message goes to the file" << std::endl;
        }
        std::cout << "Printing to the screen again" << std::endl;
    }
    

    Output:

    This message is printed to the screen

    Printing to the screen again

    Contents of the file "output.txt":

    This message goes to the file

提交回复
热议问题