Boost.IOStreams:如何使用"rdbuf"正确重定向文件流?

Boost.IOStreams: How to correctly redirect file streams with 'rdbuf'?

本文关键字:重定向 文件 rdbuf IOStreams 何使用 Boost      更新时间:2023-10-16

我无法解释以下行为:

#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!");

成功。

我到底错过了什么?谢谢。

你做错了。你把streambufistringstream分配到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.