0

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 ?
Amxx
  • 3,020
  • 2
  • 24
  • 45

1 Answers1

0

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);
David G
  • 94,763
  • 41
  • 167
  • 253
  • Why does the `stringbuf` not require this? – Lightness Races in Orbit Apr 30 '15 at 16:52
  • @LightningRacisinObrit can't remember the reason, and I'm away from the book right now, but page 243 of IOStreams and Locales explains it. – David G Apr 30 '15 at 17:20
  • If I am alterning between read and write, I and just `pubseekpos(0)` each time it will bring me back to the begining rather then after the last read element. Is there any better way then kipping a counter with the "read so far" size ? – Amxx Apr 30 '15 at 17:21
  • @Amxx There's no standard way to do that. And I know of no easy way other than keeping a counter. You *could* build a stream buffer that does this automatically, but it's non-trivial. – David G Apr 30 '15 at 17:32