Boost.IOStreams:如何使用"rdbuf"正确重定向文件流?
Boost.IOStreams: How to correctly redirect file streams with 'rdbuf'?
我无法解释以下行为:
#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!");
成功。
我到底错过了什么?谢谢。
你做错了。你把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.
相关文章:
- 获取通过重定向传入的输入文件的名称?
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 将 clangd stderr 重定向到文件而不是控制台
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 可以将Boost消息队列文件重定向到用户指定的位置
- 如何使用PHP将上传到本地主机的一个html文件重定向到磁盘上的另一个html文档
- 尝试将 std::cerr 重定向到文件时出现访问冲突异常
- 重定向到文件的C ++ COUT比使用Ofstream慢
- 将 Tcl 中的命令输出重定向到文件时,文件以 DOS 格式生成
- 将 c++ 程序语法错误重定向到窗口中的文件
- 如何在没有任何缓冲区的情况下将 stderr 重定向到文件?
- 将 ffmpeg 控制台输出重定向到C++中的字符串或文件
- Win32 GUI C(++) 应用将标准输出和标准输出重定向到磁盘上的同一文件
- 即使可执行文件的输入是从文件重定向的,如何强制从终端输入?
- C++输入重定向导致文件参数工作时出错
- C++ vector<pair<int,int>> std::all_of() 函数问题(重定向到头文件)
- 重定向文件访问
- Boost.IOStreams:如何使用"rdbuf"正确重定向文件流?