关于rdbuf

75 篇文章 0 订阅
72 篇文章 0 订阅
rdbuf来重定向流 在SF的的collect.cpp中的collect函数中,使用了rdbuf来将标准输出重定向到日志文件。

            // 重定向日志输出
            ofstream file((LOG_PATH + "collect/" + fileName + ".log").c_str());
            streambuf* buffer = cout.rdbuf(); //oldbuffer,STDOUT的缓冲区
            cout.rdbuf(file.rdbuf());

            // 恢复输出的重定向
            cout.rdbuf(buffer); //重新载入STDOUT的缓冲区

下面是CPP Reference上的解释:
streambuf* rdbuf ( ) const;streambuf* rdbuf ( streambuf* sb );
 
 

Get/set the associated stream buffer

The first syntax returns the stream buffer object associated with the stream.

The second syntax associates the stream with sb and returns the stream buffer object previously associated with the stream. In this case, the buffer's control state is set to goodbit as if a call to member clear().

Parameters
sb
A pointer to the stream buffer object to associate the stream with.
Return Value
A pointer to the stream buffer object associated with the stream before the call

另外在CSDN上面以为老兄的帖子中,还绝伦一个例子,并提出了两个需要注意的地方,我感觉比较重要,就贴过来了。


#include 

#include 

int main()

{

    std::ofstream log("foo.log");

    std::streambuf *oldbuf = std::cout.rdbuf(log.rdbuf());

    std::cout << "输出到标准输出,但实际输出到了foo.log文件中\n";

log << "输出到文件,虽然将cout重定向到了log,但不影响log本身的使用\n";

      // 恢复流缓冲区

    std::cout.rdbuf(oldbuf);

}

 

注意:

1.cout可以调用rdbuf来替换缓冲区,但log不能通过调用rdbuf来替换缓冲区。因为ofstream的rdbuf并没有同样的功能。

2.对流的重定向,只是作用在一个代码块内{},出了这个{},就恢复为原来的了,但是对在这个代码块内调用的函数,重定向也会生效。
basic_streambuf<charT,traits> * rdbuf ( basic_streambuf<charT,traits> sb );
 
 
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值