我正在编写一个代码,必须在控制台上打印相同的数据并打印到文件中。
有没有办法填充公共输出流对象,然后使用 cout 将其显示在控制台上,并使用 fstream 和 iostream 库将其导出到文件?
当然。您只需创建一个合适的流缓冲区,它可能存储到它内部写入的其他流缓冲区。然后使用这个流缓冲区创建一个std::ostream
你正在写信给.
例如,以下是此方法的简单实现:
#include <streambuf>
#include <ostream>
class teebuf
: public std::streambuf
{
std::streambuf* sb1_;
std::streambuf* sb2_;
int overflow(int c) {
typedef std::streambuf::traits_type traits;
bool rc(true);
if (!traits::eq_int_type(traits::eof(), c)) {
traits::eq_int_type(this->sb1_->sputc(c), traits::eof())
&& (rc = false);
traits::eq_int_type(this->sb2_->sputc(c), traits::eof())
&& (rc = false);
}
return rc? traits::not_eof(c): traits::eof();
}
int sync() {
bool rc(false);
this->sb1_->pubsync() != -1 || (rc = false);
this->sb2_->pubsync() != -1 || (rc = false);
return rc? -1: 0;
}
public:
teebuf(std::streambuf* sb1, std::streambuf* sb2)
: sb1_(sb1), sb2_(sb2) {
}
};
class oteestream
: private virtual teebuf
, public std::ostream {
public:
oteestream(std::ostream& out1, std::ostream& out2)
: teebuf(out1.rdbuf(), out2.rdbuf())
, std::ostream(this) {
this->init(this);
}
};
#include <fstream>
#include <iostream>
int main()
{
std::ofstream fout("tee.txt");
oteestream tee(fout, std::cout);
tee << "hello, world!\n";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)