我需要将std :: cout的副本重定向到该文件.即我需要在控制台和文件中看到输出.如果我用这个:
// 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; }
解决方法
您可以做的最简单的事情是创建一个输出流类来执行此操作:
#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我目前无法检查文件输出是否正确完成,尽管它不应该是一个问题.