替换std::ofstream底层rdbuf为std::stringstream后文件为空问题
问题分析与解决
你代码的核心问题是误解了rdbuf()成员函数的作用:调用static_cast<std::ostream&>(ofs).rdbuf(ss.rdbuf())是替换ofs关联的流缓冲区,而非将ss的内容写入ofs。
具体原因:
- 执行该语句后,ofs会放弃原本关联的文件流缓冲区,转而使用ss的内存缓冲区。这一步没有任何数据拷贝或写入操作,只是完成了缓冲区对象的绑定切换。
- 程序结束时,ofs的RAII机制会刷新并关闭当前绑定的缓冲区——也就是ss的内存缓冲区,这对
out.txt文件没有任何影响,因为ofs已经和文件缓冲区解绑。 - 被替换下来的原文件缓冲区中没有任何数据(你从未向ofs写入过内容),所以最终文件为空。
正确的实现方式
如果你想把ss的内容写入out.txt,有两种直接有效的写法:
方式一:通过流输出操作转发缓冲区内容
#include <fstream> #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"; ofs << ss.rdbuf(); // 将ss缓冲区的内容写入ofs }
方式二:直接输出ss的字符串内容
#include <fstream> #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"; ofs << ss.str(); // 输出ss的字符串内容到ofs }
这两种方式都会将ss中的数据写入ofs关联的文件缓冲区,程序结束时ofs的RAII机制会自动刷新缓冲区到磁盘,最终out.txt会包含预期内容。
内容的提问来源于stack exchange,提问作者psb
相关产品推荐
相关产品推荐

