绕道cout到自定义功能

时间:2015-12-12 19:21:06

标签: c++ hook

我做了一个非常大的程序,它一直在屏幕上打印很多信息。 问题是我不能一直在那里阅读并最终发现错误。所以我想出了将cout打印的所有内容写入文件的想法。 问题是,我已经写过,有很多" cout"。完成整个代码并用自定义函数替换每个cout会非常烦人。

我有什么方法可以"勾选" cout被重定向到我的自定义函数?

2 个答案:

答案 0 :(得分:3)

您可以通过rdbuf方法提供自定义流缓冲区。以下是将cout重定向到文件的示例:

std::ofstream ofs("output");
std::cout.rdbuf(ofs.rdbuf());

答案 1 :(得分:2)

您可以使用带有输出重定向的命令行将标准输出直接重定向到文件

fileneame.exe > log.txt
     or
./filename > log.txt

否则使用一些RAII,如下所示:

class Logger
{
    std::ofstream filehandle;
    std::ostream&   myStream;
    std::streambuf* mySavedStreambuf;

public:
    Logger( std::ostream& oldStream, std::string const& filename)
        : filehandle(filename)
        , myStream(oldStream)
        , mySavedStreambuf(oldStream.rdbuf())
    {
        oldStream.rdbuf(filehandle.rdbuf());
    }
    ~Logger()
    {
        myStream.rdbuf(mySavedStreambuf);
    }
};

然后在你的intilization / main例程中执行类似的操作:

int main()
{

 {
      Logger temp( std::cout, "log.txt" );
      // call funcs that has std::cout, all outputs will be in log.txt
 }// temp goes out of scope, std::cout restored.

 // Call funcs that has std::cout, now all outputs on standard ouput.

}