Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 同时写入终端和文件c++;_C++_Stdout_Fclose_Freopen - Fatal编程技术网

C++ 同时写入终端和文件c++;

C++ 同时写入终端和文件c++;,c++,stdout,fclose,freopen,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; } int main() { freopen(“myfile.txt”,“w”,stdout); cout没有一个内置的方法可以

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

我想把我的C++程序的所有输出写入终端和输出文件。使用类似这样的方法:

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

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


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

可能的解决方案:使用静态流类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;
}
struct日志流
{

模板LogStream&operator我有一种方法可以做到这一点,它基于订户模型

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

出于您的目的,您创建了两个订阅服务器,一个输出到文件,另一个输出到控制台


在代码的逻辑中,您只需输出消息,在这个级别上,您不需要知道将如何处理它。但是在我的模型中,您可以首先检查是否有“侦听器”,因为这被认为比构建和输出只以/dev/null结尾的消息更便宜(您知道我的意思).

实现这一点的一种方法是编写一个小包装器,例如:

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;
}
类输出
{
公众:
//在构造函数或任何其他方法中打开该文件
双输出(常量std::字符串和文件名);
// ...
//在此处写入文件和流
模板

friend DoubleOutput&Operator您使用的是另一个stream对象,该对象将调用复制到一个文件和stdout的可能副本。我认为您需要对答案进行一点扩展。它在当前形式下不起作用。@Aly:如果您满意,您介意接受此答案以便将问题标记为“已解决”吗?谢谢。或者,你可以发布你自己的答案并接受它。因为这是一个很好的答案,所以投了更高的票;但是,对于OP想要的东西来说,它可能太重了。
DoubleOutput mystream("myfile");
mystream << "Hello World";