read and write from a filebuf using iostream

796 Views Asked by At

When allocating an iostream from a stringbuf, everything works well

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

However if I try to change my stringbuf to use a filebuf it doesn't work anymore

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

...

0 0

ghex tels me "/tmp/buffer.dat" contains what it's suppose to.

  • Is it possible to read and write from a filebuf without closing and reopening the file ?
1

There are 1 best solutions below

4
David G On

You need to seek the buffer back to the beginning before you continue reading:

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

fs.pubseekpos(0);

fs.read(&x, 1);
fs.read(&y, 1);