将cout重定向到文件c ++中 [英] redirecting cout into file c++

查看:501
本文介绍了将cout重定向到文件c ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我有一对夫妇的cout在项目中的各种文件。我希望所有的重定向并保存在 .txt 文件,我现在实现的是,只有一个cout被保存在文件中。我不想为每个 cout 创建单独的 .txt ,以便一次阅读。我的代码看起来像这样:

my problem is I have a couple of cout's in various files in the project. I would like all of them to be redirected and saved in .txt file, and what I achieved by now is that only one cout is saved in the file. I don't want to create separate .txt for each cout, for the sake of reading them at once. My code looks now like this:

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::ofstream out("out.txt");
    std::cout.rdbuf(out.rdbuf()); 

    std::cout << "get it3";
    std::cout << "get it4"; 
}

cout 都在一个文件中,

推荐答案

显而易见的,它们是两个不同的,如何重定向并保存在一个 .txt 答案是你不应该输出到
std :: cout 。所有实际输出应该是 std :: ostream&
,它可以设置为 std :: cout 默认情况下,但是你可以
初始化为其他事情。

The obvious answer is that you should never output to std::cout. All actual output should be to an std::ostream&, which may be set to std::cout by default, but which you can initialize to other things as well.

另一个明显的答案是重定向应该在
之前

Another obvious answer is that redirection should be done before starting the process.

但是,假设不能将输出
的代码更改为 std :: cout ,并且你不能控制
你的程序的调用(或者你只想改变一些输出),
你可以改变输出 std :: cout 本身通过附加
a不同 streambuf 。在这种情况下,我也使用RAII,
确保当你退出时, std :: cout 有它
期望的streambuf。但类似以下内容应该工作:

Supposing, however, that you cannot change the code outputting to std::cout, and that you cannot control the invocation of your program (or you only want to change some of the outputs), you can change the output of std::cout itself by attaching a different streambuf. In this case, I'd use RAII as well, to ensure that when you exit, std::cout has the streambuf it expects. But something like the following should work:

class TemporaryFilebuf : public std::filebuf
{
    std::ostream&   myStream;
    std::streambuf* mySavedStreambuf;
public:
    TemporaryFilebuf(
            std::ostream& toBeChanged,
            std::string const& filename )
        : std::filebuf( filename.c_str(), std::ios_base::out )
        , myStream( toBeChanged )
        , mySavedStreambuf( toBeChanged.rdbuf() )
    {
        toBeChanged.rdbuf( this );
    }
    ~TemporaryFilebuf()
    {
        myStream.rdbuf( mySavedStreambuf );
    }
};

(您可能需要添加一些错误处理;例如,如果
无法打开该文件。)

(You'll probably want to add some error handling; e.g. if you cannot open the file.)

当您进入要重定向输出的区域时,只需
创建一个流的实例( std :: cout 或任何其他
ostream )和文件的名称。当实例
被销毁时,输出流将恢复输出到
,无论它在什么时候输出。

When you enter the zone where you wish to redirect output, just create an instance with the stream (std::cout, or any other ostream) and the name of the file. When the instance is destructed, the output stream will resume outputting to whereever it was outputting before.

这篇关于将cout重定向到文件c ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆