【问题标题】:Writing to both terminal and file c++写入终端和文件 c++
【发布时间】:2014-01-20 11:13:55
【问题描述】:

我发现这个问题是针对 Python、Java、Linux 脚本而不是 C++ 回答的:

我想将我的 C++ 程序的所有输出都写入终端和输出文件。使用这样的东西:

int main ()
{
freopen ("myfile.txt","w",stdout);
cout<< "Let's try this"; 
fclose (stdout);
return 0;
}

仅将其输出到名为“myfile.txt”的输出文件,并防止其显示在终端上。我怎样才能让它同时输出到两者?我使用 Visual Studio 2010 Express(如果这有什么不同的话)。

提前致谢!

【问题讨论】:

标签: c++ stdout fclose freopen


【解决方案1】:

可能的解决方案:使用静态流类 cout 对象同时写入 cout 和文件。

粗略的例子:

struct LogStream 
{
    template<typename T> LogStream& operator<<(const T& mValue)
    {
        std::cout << mValue;
        someLogStream << mValue;
    }
};

inline LogStream& lo() { static LogStream l; return l; }

int main()
{
    lo() << "hello!";
    return 0;
}

不过,您可能需要显式处理流操纵器。

Here is my library implementation.

【讨论】:

  • @Aly:如果您满意,您介意接受这个答案,以便将问题标记为“已解决”吗?谢谢。或者,您可以发布自己的答案并接受。
【解决方案2】:

没有内置的方法可以一步完成。您必须将数据写入文件,然后分两步将数据写入屏幕。

您可以编写一个函数来接收数据和文件名并为您执行此操作,以节省您的时间,某种记录功能。

【讨论】:

    【解决方案3】:

    我有一个方法可以做到这一点,它基于订阅者模型。

    在此模型中,您的所有日志记录都转到“日志记录”管理器,然后您有“订阅者”来决定如何处理消息。消息有主题(对我来说是一个数字),记录器订阅一个或多个主题。

    出于您的目的,您创建了 2 个订阅者,一个输出到文件,一个输出到控制台。

    在您的代码逻辑中,您只需输出消息,在此级别不需要知道将要使用它做什么。在我的模型中,虽然您可以先检查是否有任何“侦听器”,因为这被认为比构建和输出仅以 /dev/null 结尾的消息更便宜(你知道我的意思)。

    【讨论】:

    • 赞成,因为这是一个很好的答案;但是,对于 OP 想要的东西来说,它可能太重了。
    【解决方案4】:

    一种方法是编写一个小包装器来执行此操作,例如:

    class DoubleOutput
    {
    public:
      // Open the file in the constructor or any other method
      DoubleOutput(const std::string &filename);   
      // ...
      // Write to both the file and the stream here
      template <typename T>
      friend DoubleOutput & operator<<(const T& file);
    // ...
    private:
      FILE *file;
    }
    

    使用类而不是函数使您使用 RAII 成语 (https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization)

    使用它:

    DoubleOutput mystream("myfile");
    mystream << "Hello World";
    

    【讨论】:

    • 我认为您需要稍微扩展答案。它不适用于当前形式。
    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多