Next: , Previous: mktemp, Up: Stdio


4.35 open_memstream—open a write stream around an arbitrary-length string

Synopsis

     #include <stdio.h>
     FILE *open_memstream(char **restrict buf,
         size_t *restrict size);
     

Description
open_memstream creates a seekable FILE stream that wraps an arbitrary-length buffer, created as if by malloc. The current contents of *buf are ignored; this implementation uses *size as a hint of the maximum size expected, but does not fail if the hint was wrong. The parameters buf and size are later stored through following any call to fflush or fclose, set to the current address and usable size of the allocated string; although after fflush, the pointer is only valid until another stream operation that results in a write. Behavior is undefined if the user alters either *buf or *size prior to fclose.

The stream is write-only, since the user can directly read *buf after a flush; see fmemopen for a way to wrap a string with a readable stream. The user is responsible for calling free on the final *buf after fclose.

Any time the stream is flushed, a NUL byte is written at the current position (but is not counted in the buffer length), so that the string is always NUL-terminated after at most *size bytes. However, data previously written beyond the current stream offset is not lost, and the NUL byte written during a flush is restored to its previous value when seeking elsewhere in the string.


Returns
The return value is an open FILE pointer on success. On error, NULL is returned, and errno will be set to EINVAL if buf or size is NULL, ENOMEM if memory could not be allocated, or EMFILE if too many streams are already open.


Portability
This function is being added to POSIX 200x, but is not in POSIX 2001.

Supporting OS subroutines required: sbrk.