我一直在寻找一种方法来实现一种将cout,cerr等输出到控制台和文件的方法,不幸的是我对缓冲区的了解非常缺乏,所以详细解释一切都在做什么。非常好。
我能做的最令人印象深刻的事情是:
//Includes not shown
std::ofstream file ("out.txt");
std::streambuf* fileSb = file.rdbuf();
cout.rdbuf(fileSb);
但即使我的知识有限,我也会根据我对结构看起来的研究得出一些想法:
#include <iostream>
#include <fstream>
#include "dualBuffer.h"
int main () {
std::ofstream file ("out.txt");
dualBuffer(cout, file);
std::cout << "Hellow world!" << std::endl; //This outputs to console and file
}
#include <iostream>
class dualBuffer : public streambuf /*Maybe ostream as well ????*/ {
public:
dualBuffer (std::ostream & os1, std::ostream& os2)
: *os1b ( os1.rdbuf() )
, *os1b ( os2.rebuf() )
{ }
//Another constructor if streambuf* is passed instead
private:
std::streambuf *os1b, *os2b;
}
//May have typos or bugs
其中一个要求是它全部构建在标准库之上,没有任何外部或OS依赖,另一个是我想要它,以便cout在程序的每个部分中具有相同的属性,在dualBuffer构造函数之后完成它的事情
答案 0 :(得分:0)
您的要求会改变cout的正常行为,这会使代码混乱。 为什么不使用另一个类来做这个。就像这样:
#include <fstream>
#include <iostream>
class GeneralOStream
{
public:
GeneralOStream(std::ostream& stdStream, std::ostream& fileStream)
:_stdStream(stdStream)
, _fileStream(fileStream)
{
}
template<typename T>
friend GeneralOStream& operator << (GeneralOStream& stream, const T& t);
private:
std::ostream& _stdStream;
std::ostream& _fileStream;
};
template<typename T>
GeneralOStream& operator << (GeneralOStream& stream, const T& t)
{
stream._stdStream << t;
stream._fileStream << t;
return stream;
}
int main()
{
std::ofstream file("out.txt");
GeneralOStream gos(std::cout, file);
std::cout << "Hellow world!" << std::endl; //This outputs to console and file
}