提问人:psb 提问时间:5/8/2023 更新时间:5/9/2023 访问量:51
将 std::ofstream 的底层 rdbuf 替换为 std::stringstream 的底层 rdbuf
Substitute std::ofstream's underlying rdbuf with std::stringstream's underlying rdbuf
问:
#include <fstream>
#include <ostream>
#include <sstream>
int main(int /*argc*/, char** /*argv*/)
{
auto ofs = std::ofstream{"out.txt"};
if (!ofs) { throw std::runtime_error{"ofstream"}; }
auto ss = std::stringstream{};
ss << "Hello world\n";
static_cast<std::ostream&>(ofs).rdbuf(ss.rdbuf());
}
我认为在程序结束时将要发生的事情是 RAII 关闭,并且 的缓冲区内容将被写入 。但空的。我做错了什么?ofs
ss
out.txt
out.txt
答:
4赞
Alan Birtles
5/8/2023
#1
std::ofstream
的默认缓冲区是 std::filebuf
,它用于管理对文件的写入。通过将该缓冲区替换为 std::stringbuf
,您可以有效地将文件流转换为字符串流,其中对 的任何写入都将转到内存中的 a 而不是文件。std::ofstream
std::string
如果您实际想做的是将 的缓冲区的内容写入文件,则可以改为这样做:std::stringstream
ofs << ss.rdbuf();
评论
ofs
std::ostream
ofs
rdbuf