写入终端和文件c ++

时间:2014-01-20 11:13:55

标签: c++ stdout fclose freopen

我发现这个问题适用于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(如果这会有所不同)。

提前致谢!

4 个答案:

答案 0 :(得分:5)

可能的解决方案:使用类似静态流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.

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

我有一种方法可以做到这一点,它基于用户模型。

在此模型中,所有日志记录都会转到“日志记录”管理器,然后您就会有“订阅者”来决定如何处理这些消息。消息包含主题(对我而言)和记录器订阅一个或多个主题。

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

在代码的逻辑中,您只需输出消息,在此级别不需要知道将要执行的操作。在我的模型中虽然你可以先检查是否有任何“听众”,因为这被认为比构建和输出只会以/ dev / null结尾的消息便宜(你知道我的意思)。

答案 3 :(得分:0)

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

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";