将std :: cout的副本重定向到该文件 [英] Redirect the copy of std::cout to the file
本文介绍了将std :: cout的副本重定向到该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将std :: cout的副本重定向到该文件。也就是说我需要看到在控制台和文件中的输出。如果我使用这个:
I need redirect the copy of std::cout to the file. I.e. I need see the output in console, and in file. If I use this:
// redirecting cout's output
#include <iostream>
#include <fstream>
using namespace std;
int main () {
streambuf *psbuf, *backup;
ofstream filestr;
filestr.open ("c:\\temp\\test.txt");
backup = cout.rdbuf(); // back up cout's streambuf
psbuf = filestr.rdbuf(); // get file's streambuf
cout.rdbuf(psbuf); // assign streambuf to cout
cout << "This is written to the file";
cout.rdbuf(backup); // restore cout's original streambuf
filestr.close();
return 0;
}
然后我写字符串到文件,
then I write string to the file, but I see the nothing in console. How can I do it?
推荐答案
最简单的方法就是创建一个输出流类来实现这一点:
The simplest you can do is create an output stream class that does this:
#include <iostream>
#include <fstream>
class my_ostream
{
public:
my_ostream() : my_fstream("some_file.txt") {}; // check if opening file succeeded!!
// for regular output of variables and stuff
template<typename T> my_ostream& operator<<(const T& something)
{
std::cout << something;
my_fstream << something;
return *this;
}
// for manipulators like std::endl
typedef std::ostream& (*stream_function)(std::ostream&);
my_ostream& operator<<(stream_function func)
{
func(std::cout);
func(my_fstream);
return *this;
}
private:
std::ofstream my_fstream;
};
请参阅此代码的此ideone链接: http://ideone.com/T5Cy1M
我目前无法检查文件输出是否正确,虽然它不应该是一个问题。
See this ideone link for this code in action: http://ideone.com/T5Cy1M I can't currently check if the file output is done correctly though it shouldn't be a problem.
这篇关于将std :: cout的副本重定向到该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文