rdbuf,重定向

来源:互联网 发布:沥青混合料油石比数据 编辑:程序博客网 时间:2024/05/17 02:48

std::ios::rdbuf

get (1)
streambuf* rdbuf() const;
set (2)
streambuf* rdbuf (streambuf* sb);
Get/set stream buffer
返回或者设置流缓冲区
The first form (1) returns a pointer to the stream buffer object currently associated with the stream.
第一个形式,返回一个指向被关联的stream buffer对象指针
The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears theerror state flags.
第二个形式,设置流对象 sb(参数) 作为stream buffer并且清除流的错误标志(像 bad , eof good...)

If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit).
如果对象是一个空指针,这个函数将会自动将流badbit置为错误标志。如果异常被传递(设置)badbit将会抛出一个异常。

Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on thatinternal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer(although input/output operations on streams always use the associated stream buffer, as returned by this member function).
一些派生的流类(如stringstream和fstream)维持自己的内部流缓冲区,它们是相关的建设。调用这个函数来改变相关的流缓冲区将对内部流缓冲区无影响:流将有一个关联的流缓冲区具有不同于其内部流缓冲(虽然流输入/输出操作总是使用相关的流缓冲区,将由该成员函数返回)。

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// redirecting cout's output thrrough its stream buffer#include <iostream>     // std::streambuf, std::cout#include <fstream>      // std::ofstreamint main () {  std::streambuf *psbuf, *backup;  std::ofstream filestr;  filestr.open ("test.txt");  backup = std::cout.rdbuf();     // back up cout's streambuf  psbuf = filestr.rdbuf();        // get file's streambuf  std::cout.rdbuf(psbuf);         // assign streambuf to cout  std::cout << "This is written to the file";  std::cout.rdbuf(backup);        // restore cout's original streambuf  filestr.close();  return 0;}

来自cplusplus.com,水平有限!

0 0
原创粉丝点击