C++正确的清理重定向缓冲区
C++ proper cleanup redirected buffer for tee ostream
我需要将消息输出到控制台和日志文件。在谷歌搜索之后,我学会了"teebuf"概念,它基本上创建了一个从basic_streambuf继承的自定义类。这工作正常,但如何正确清理重定向的缓冲区。我的意思是如何为"tee"缓冲区实现 RAII,这样我就不需要每次需要退出程序时都打扰它。
备注:目前使用提升库对我来说不是一个选择。
代码段
int main() {
std::streambuf* cout_sbuf = std::cout.rdbuf();
std::ofstream fout(fileOutDebug);
teeoutbuf teeout(std::cout.rdbuf(), fout.rdbuf());
std::cout.rdbuf(&teeout);
// some code ...
if (failed) {
std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
return -1;
}
// some more code ...
std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
return 0;
}
代码段(我的试用版实现,但失败)
template < typename CharT, typename Traits = std::char_traits<CharT>
> class basic_tostream : std::basic_ostream<CharT, Traits>
{
public:
basic_tostream(std::basic_ostream<CharT, Traits> & o1,
std::basic_ostream<CharT, Traits> & o2)
: std::basic_ostream<CharT, Traits>(&tbuf),
tbuf(o1.rdbuf(), o2.rdbuf()) {}
void print(char* msg);
private:
basic_teebuf<CharT, Traits> tbuf; // internal buffer (tee-version)
};
typedef basic_tostream<char> tostream;
int main() {
std::ofstream fout(fileOutDebug);
tostream tee(std::cout, fout, verbose);
tee << "test 1n"; // <-- compile error
tee.print("sometext"); // <-- comment above and it run fine, both file and console written
}
错误消息:"std::basic_ostream"是无法访问的"basic_tostream"基础
你应该使用:
template < typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : public std::basic_ostream<CharT, Traits>
而不是:
template < typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : std::basic_ostream<CharT, Traits>
关键区别在于public
。这就是'std::basic_ostream' is an inaccessible base of 'basic_tostream'
错误消息的内容。
相关文章:
- 如何将stdout重定向到stderr
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- Windows C++重定向库
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 使用 dup2() 进行输入重定向
- 将 clangd stderr 重定向到文件而不是控制台
- 如何在C++中获取重定向网页的URL
- 将标准输出重定向到ostream
- 如何撤消此代码上的 cin 重定向?
- 使用重定向标准处理子进程中的 kbhit
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 如何将HTTPS流量重定向到本地主机:443上的代理?
- 如何在没有任何缓冲区的情况下将 stderr 重定向到文件?
- C++正确的清理重定向缓冲区
- 将文件句柄重定向到字符缓冲区
- 重定向子进程输出到缓冲区
- 将标准输出重定向到缓冲区,不使用>
- 重定向计数到用winapi创建的新缓冲区