将 std::ofstream 的底层 rdbuf 替换为 std::stringstream 的底层 rdbuf

Substitute std::ofstream's underlying rdbuf with std::stringstream's underlying rdbuf

提问人:psb 提问时间:5/8/2023 更新时间:5/9/2023 访问量:51

问:

#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 关闭,并且 的缓冲区内容将被写入 。但空的。我做错了什么?ofsssout.txtout.txt

C++ IO StringStream ofStream

评论

0赞 Some programmer dude 5/8/2023
为什么是演员阵容?由于继承,已经是一个ofsstd::ostream
3赞 BoP 5/8/2023
“我做错了什么?”实际写入的是 filebuf,而不是 fstream。
1赞 john 5/8/2023
具体而言,您的代码不会调用此方法,这是写入发生和文件关闭的地方。
0赞 Alan Birtles 5/8/2023
@john缓冲区在销毁时仍会关闭和销毁,因此不会更改缓冲区的所有权ofsrdbuf
0赞 john 5/8/2023
@AlanBirtles 是的,缓冲区已关闭,但由于它是错误的缓冲区,因此文件不会关闭。

答:

4赞 Alan Birtles 5/8/2023 #1

std::ofstream的默认缓冲区是 std::filebuf,它用于管理对文件的写入。通过将该缓冲区替换为 std::stringbuf,您可以有效地将文件流转换为字符串流,其中对 的任何写入都将转到内存中的 a 而不是文件。std::ofstreamstd::string

如果您实际想做的是将 的缓冲区的内容写入文件,则可以改为这样做:std::stringstream

ofs << ss.rdbuf();