3

I create a stream by open_memstream(), fill it and then read. It works fine. But I'm confused that function documentation says: "The open_memstream() function opens a stream for writing to a buffer". But I can read it too. Does I use it in a proper way? Maybe I can read the stream because of function implementation in my platform allows to do that? And when I change a platform I will probably get an error.

Sharf
  • 31
  • 2
  • 5
  • Even if it's well defined to read from the file-stream, I don't see much of a use-case for it. The main use-case I see for using e.g. `open_memstream` or `fmemopen` is to be able to use the `printf` function to format strings into memory, and reading from the file doesn't make much sense then because you can just as well read directly from the memory. And if all you are doing is formatting strings into memory, you should probably be using [`std::ostringstream`](http://en.cppreference.com/w/cpp/io/basic_ostringstream) when programming in C++. – Some programmer dude Jun 04 '15 at 11:30
  • This is a pretty good question. – Lightness Races in Orbit Jun 04 '15 at 12:07

2 Answers2

6

But I can read it too. Does I use it in a proper way?

No, not really. Posix specifies open_memstream() is for output only. You're only supposed to write to it. You can access the data you write via the buffer created by open_memstream(), but not with fread(), fgets() or similar.

Use fmemopen() if you want a stream you can read from too.

Maybe I can read the stream because of function implementation in my platform allows to do that?

Yes, it might be an feature of the implementation that allows you to read from the FILE* too, check its documentation.

nos
  • 223,662
  • 58
  • 417
  • 506
  • Thank you for you answer. Now I open a stream by open_memstream(), fill it, close the stream and open resulting buffer in fmemopen() for reading. P.S. I cannot use fmemopen() immediately because the buffer has a dynamic size. – Sharf Jun 04 '15 at 12:22
1

To complete nos's answer:

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
  • @iBug I've updated the links. For redirects that use my GH pages as a shortener, I will have to do it more calmly later on to avoid breaking stuff, but the redirect targets are now https. You guys from USTC truly are the most anti commie, I love it. – Ciro Santilli OurBigBook.com Sep 20 '17 at 05:17