How to override cout in C++?

前端 未结 9 1423
礼貌的吻别
礼貌的吻别 2020-12-07 02:47

I have a requirement, I need to use printf and cout to display the data into console and file as well. For printf I have

9条回答
  •  既然无缘
    2020-12-07 03:43

    I assume you have some code using std::cout and printf which you cannot modify, otherwise the most simple way to solve your problem would be to write to a different stream from cout and use fprintf rather than or in conjunction with printf.

    By following that approach you could define both a new stream class that actually wrote both to standard output and to a given file, as well as a function that combined calls to both printf and fprintf.

    However a much simpler approach is to use the tee program, originally from UNIX, which copies its input both to output and to a given file. With that you could simply call your program in this way:

    your_program | tee your_log_file
    

    Answers to this question lead to a few alternative implementations available for Windows. Personally I always install cygwin on my PC's to have UNIX/Linux utilities available.

提交回复
热议问题