Next: , Previous: , Up: Stdio   [Contents][Index]


4.43 open_memstream, open_wmemstream—open a write stream around an arbitrary-length string

Synopsis

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

#include <wchar.h>
FILE *open_wmemstream(wchar_t **restrict buf,
    size_t *restrict size);

Description
open_memstream creates a seekable, byte-oriented 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.

open_wmemstream is like open_memstream just with the associated stream being wide-oriented. The size set in size in subsequent operations is the number of wide characters.

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 (or wide characters in case of open_wmemstream). However, data previously written beyond the current stream offset is not lost, and the NUL value 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
POSIX.1-2008

Supporting OS subroutines required: sbrk.



Next: , Previous: , Up: Stdio   [Contents][Index]