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/               
      *************************************************************************/

  • 相关阅读:
    列表,字典,元组,集合内置方法
    数据类型内置方法(1)
    if判断与while、for循环语句
    与用户交互、格式化输出、基本运算符
    执行python程序的两种方式
    # 操作系统与编程语言分类
    drf框架2-序列化与反序列化
    drf框架1
    前端-vue路由传参、axios前后台交互、cookie设置
    前端-vue的配置和使用
  • 原文地址:https://www.cnblogs.com/submarinex/p/2964756.html
Copyright © 2011-2022 走看看