C++流重定向到文件

《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——

你可能感兴趣的:(C++)