《C++标准程序库》 13.10.3 将标准 Streams 重新定向(Redirecting)
通过“设置 stream 缓冲区”来重定向某个 sream。“设置 stream 缓冲区”意味 I/O stream 的重定向可由程控,不必借助操作系统。
1 #include <iostream>
2 #include <fstream>
3
4 using namespace std;
5
6 void Redirect(ostream &);
7
8 int main()
9 {
10 cout << "the first row" << endl;
11
12 Redirect(cout);
13
14 cout << "the last row" << endl;
15
16 return 0;
17 }
18
19 void Redirect(ostream &strm)
20 {
21 ofstream file("redirect.txt");
22
23 // save output buffer of the stream
24 streambuf *strm_buffer = strm.rdbuf();
25
26 // redirect output into the file
27 strm.rdbuf(file.rdbuf());
28
29 file << "one row for the file" << endl;
30 strm << "one row for the stream" << endl;
31
32 // restore old output buffer
33 strm.rdbuf(strm_buffer);
34 } // closes file AND its buffer automatically
程序输出:
the first row
the last row
文件内容:
1 one row for the file
2 one row for the stream
值得注意的是,在 void Redirect(ostream &) 中的 file 是局部对象,在函数结束时被销毁,相应的 stream 缓冲区也一并被销毁。这和标准的 streams 不同,因为通常 file streams 在构造过程分配 stream 缓冲区,并于析构时销毁它们。所以以上例子中的 cout 不能在被用于写入。事实上它甚至无法在程序结束时被安全销毁。因此我们应该保留旧缓冲区并于事后恢复。
——EOF——
原文链接: https://www.cnblogs.com/submarinex/archive/2013/03/17/2964756.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/80851
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!