【问题标题】:C++ writing to std::out and std:clog simultaneouslyC++ 同时写入 std::out 和 std:clog
【发布时间】:2015-01-14 07:45:52
【问题描述】:

我想创建一个类似流的类,通过它我可以同时写入std::outstd::clog

我有以下代码,但问题是它只写入std::clog,而控制台上的输出与预期不符(奇怪的是,它会覆盖自己)。

struct Log : public std::ofstream
{
    Log(const std::string filename)
    : std::ofstream(filename.c_str())
    {
        std::clog.rdbuf(this->rdbuf());
    }
};

template <typename T>
Log & operator << (Log & stream, const T & x)
{
    std::cout << x;
    std::clog << x;
    return stream;
};

我想要的是这个

Log log("logfile.txt");
log << "this should go to the console and the logfile" << 1234 << std::endl;

这个可以吗?

【问题讨论】:

  • 我应该补充一点,我想保持 std::out 不变,因为我想在我的代码的其他部分“按原样”使用它。

标签: c++ cout ofstream clog


【解决方案1】:

我找到了一个(或“那个”)解决方案!

我添加了以下代码:

Log & operator << (Log & stream, std::ostream & (*f)(std::ostream&))
{
    std::cout << f;
    std::clog << f;
    return stream;
}

这增加了也接受的功能,例如std::endl(或std::ostream 中的其他函数调用),现在的行为符合预期。

【讨论】:

    【解决方案2】:

    通常不需要手动编写这样的装置来将输出定向到多个位置。

    为此使用tee 实用程序。

    【讨论】:

    • 您可能还提到 tee 系统调用在 C 程序中的作用大致相同,这将允许用户不使用单独的程序。
    • 不确定这是否是我的解决方案。我只是想区分我写入控制台的内容和一个单独的日志文件,该文件包含与控制台上相同的信息,但还有更多额外的行。因此,我不想每次打印到控制台时都写std::cout &lt;&lt; "info"; std::clog &lt;&lt; "info"(即两次相同)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多