【问题标题】:Boost.IOStreams: How to correctly redirect file streams with 'rdbuf'?Boost.IOStreams:如何使用“rdbuf”正确重定向文件流?
【发布时间】:2016-08-15 19:55:19
【问题描述】:

我不可能找到以下行为的解释:

#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

#include <iostream>
#include <sstream>

TEST_CASE(rdbuf) {
  {
    boost::iostreams::stream<boost::iostreams::file_sink> file("test");

    file << "Hello, World!";
  }
  {
    boost::iostreams::stream<boost::iostreams::file_source> file("test");
    std::string                                             line;

    std::getline(file, line);
    CHECK_EQUAL(line, "Hello, World!");
  }
  {
    boost::iostreams::stream<boost::iostreams::file_source> file("test");
    std::istringstream                                      iss;
    std::string                                             line;

    file.rdbuf(iss.rdbuf());

    std::getline(file, line);
    CHECK_EQUAL(line, "");

    std::getline(iss, line);
    CHECK_EQUAL(line, ""); // (1) Why?
  }
  {
    boost::iostreams::stream<boost::iostreams::file_source> file("test");
    std::ostringstream                                      oss;
    std::string                                             line;

    file.rdbuf(oss.rdbuf());

    std::getline(file, line);
    CHECK_EQUAL(line, "");

    line = oss.str();
    CHECK_EQUAL(line, ""); // (2) Why?
  }
}

在(1) 和(2) 这两种情况下,我都比较期待

CHECK_EQUAL(line, "Hello, World!");

成功。

我在这里实际上想念什么?谢谢。

【问题讨论】:

    标签: c++ boost iostream io-redirection boost-iostreams


    【解决方案1】:

    你做错了。你将streambuf 从istringstream 分配给filestream,你应该在另一个方向上做。即:

    boost::iostreams::stream<boost::iostreams::file_source> file("test");
    std::istringstream                                      iss;
    std::string                                             line;
    
    iss.rdbuf(file.rdbuf()); //assign the file to iss
    
    std::getline(file, line);
    CHECK_EQUAL(line, "Hello, World!");
    
    std::getline(iss, line);
    CHECK_EQUAL(line, ""); // Empty, because the streambuf is shared.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 2010-10-30
      • 2018-09-25
      • 2017-12-13
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多