Is there a way to create a common output stream object to print on the console and to a file in c++?(有没有一种方法可以创建一个通用的输出流对象,以便在控制台上打印并在C++中打印到文件中?)
本文介绍了有没有一种方法可以创建一个通用的输出流对象,以便在控制台上打印并在C++中打印到文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一段代码,其中我必须在控制台上打印相同的数据并将其打印到文件中。 有没有办法填充通用的输出流对象,然后使用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!
";
}
这篇关于有没有一种方法可以创建一个通用的输出流对象,以便在控制台上打印并在C++中打印到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:有没有一种方法可以创建一个通用的输出流对象,以便在控制台上打印并在C++中打印到文件中?
基础教程推荐
猜你喜欢
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
