Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5708871
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2007-10-15 19:47:03

在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 .

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);

}

 

注意:

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

2.对流的重定向,只是作用在一个代码块内{},出了这个{},就恢复为原来的了,但是对在这个代码块内调用的函数,重定向也会生效。

basic_streambuf * rdbuf ( basic_streambuf sb );


阅读(5277) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~