问题描述
我的问题是我在项目的各个文件中都有几个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 中?
Both cout are in one file, but assuming they are in two different, how to redirect and save in one .txt?
推荐答案
显而易见的答案是,您永远不要输出到 std :: cout
.所有实际输出应为 std :: ostream&
,默认情况下可以将其设置为 std :: cout
,但是您可以初始化为其他东西.
The obvious answer is that you should never output tostd::cout
. All actual output should be to an std::ostream&
,which may be set to std::cout
by default, but which you caninitialize to other things as well.
另一个明显的答案是重定向应该在开始该过程.
Another obvious answer is that redirection should be done beforestarting the process.
但是,假设您不能更改输出的代码到 std :: cout
,并且您无法控制对您的程序(或者您只想更改某些输出),您可以通过附加来更改 std :: cout
本身的输出一个不同的 streambuf
.在这种情况下,我也会使用RAII确保当您退出时, std :: cout
具有流缓冲功能期望.但类似以下内容的方法应该起作用:
Supposing, however, that you cannot change the code outputtingto std::cout
, and that you cannot control the invocation ofyour program (or you only want to change some of the outputs),you can change the output of std::cout
itself by attachinga different streambuf
. In this case, I'd use RAII as well, toensure that when you exit, std::cout
has the streambuf itexpects. 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 youcannot open the file.)
当您输入要重定向输出的区域时,只需使用流( std :: cout
或其他任何方法)创建一个实例 ostream
)和文件名.当实例是销毁后,输出流将恢复输出到无论以前输出到哪里.
When you enter the zone where you wish to redirect output, justcreate an instance with the stream (std::cout
, or any otherostream
) and the name of the file. When the instance isdestructed, the output stream will resume outputting towhereever it was outputting before.
这篇关于将Cout从C ++中的各种来源重定向到同一文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!