【问题标题】:read and write from a filebuf using iostream使用 iostream 从 filebuf 读取和写入
【发布时间】:2015-04-30 16:20:05
【问题描述】:

stringbuf 分配iostream 时,一切正常

std::stringbuf fb;
std::iostream fs(&fb);
char i = 17, j = 42;
fs.write(&i, 1);
fs.write(&j, 1);
char x, y;
fs.read(&x, 1);
fs.read(&y, 1);
std::cout << (int) x << " " << (int) y << std::endl;

17 42

但是,如果我尝试将我的 stringbuf 更改为使用 filebuf,它就不再起作用了

std::filebuf fb;
fb.open("/tmp/buffer.dat", std::ios::in | std::ios::out | std::ios::trunc);
std::iostream fs(&fb);

...

0 0

ghex 告诉我 "/tmp/buffer.dat" 包含它的假设。

  • 是否可以在不关闭和重新打开文件的情况下从filebuf 读取和写入?

【问题讨论】:

    标签: c++ iostream filebuf


    【解决方案1】:

    在继续阅读之前,您需要将缓冲区返回到开头:

    fs.write(&i, 1);
    fs.write(&j, 1);
    char x, y;
    
    fs.pubseekpos(0);
    
    fs.read(&x, 1);
    fs.read(&y, 1);
    

    【讨论】:

    • 为什么stringbuf 不需要这个?
    • @LightningRacisinObrit 不记得原因,我现在不在这本书,但 IOStreams and Locales 的第 243 页解释了它。
    • 如果我在读和写之间交替,我和pubseekpos(0) 每次都会让我回到开始,而不是在最后一个读取元素之后。有没有更好的方法,然后用“到目前为止”的大小跳过一个计数器?
    • @Amxx 没有标准的方法可以做到这一点。我知道除了保持柜台之外没有其他简单的方法。您可以构建一个自动执行此操作的流缓冲区,但这并不简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2019-02-28
    相关资源
    最近更新 更多