zoukankan      html  css  js  c++  java
  • 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——


    /**************************************************************************
                      原文来自博客园——Submarinex的博客: www.cnblogs.com/submarinex/               
      *************************************************************************/

  • 相关阅读:
    eclipse maven 插件 安装 和 配置
    Windows下 maven3.0.4的安装步骤+maven配置本地仓库
    js中转换Date日期格式
    Java 集合类详解
    java的反射机制
    Java 单例模式详解
    Http协议与TCP协议简单理解
    初识JavaScript,Ajax,jQuery,并比较三者关系
    MyBatis
    MyEclipse、Eclipse优化设置
  • 原文地址:https://www.cnblogs.com/submarinex/p/2964756.html
Copyright © 2011-2022 走看看