open_memstream, open_wmemstream Subroutines

Purpose

Open a dynamic memory buffer stream.

Library

Standard Library (libc.a)

Syntax

#include <stdio.h>
FILE *open_memstream(char **bufp, size_t *sizep); 
#include <wchar.h>
FILE *open_wmemstream(wchar_t **bufp, size_t *sizep); 

Description

The open_memstream( ) and open_wmemstream( ) functions create an I/O stream associated with a dynamically allocated memory buffer. The stream is opened for writing and will be retrievable.

The stream associated with a call to open_memstream( ) is byte-oriented.

The stream associated with a call to open_wmemstream( ) is wide-oriented.

The stream maintains a current position in the allocated buffer and a current buffer length. The position is initially set to zero (the start of the buffer). Each write to the stream will start at the current position and move this position by the number of successfully written bytes for open_memstream( ) or the number of successfully written wide characters for open_wmemstream( ). The length is initially set to zero. If a write moves the position to a value larger than the current length, the current length will be set to this position. In this case a null character for open_memstream( ) or a null wide character for open_wmemstream( ) will be appended to the current buffer. For both functions the terminating null is not included in the calculation of the buffer length.

After a successful fflush( ) or fclose( ), the pointer referenced by bufp contains the address of the buffer, and the variable pointed to by sizep contains the number of successfully written bytes for open_memstream( ) or the number of successfully written wide characters for open_wmemstream( ). The buffer is terminated by a null character for open_memstream( ) or a null wide character for open_wmemstream( ).

After a successful fflush( ) the pointer referenced by bufp and the variable referenced by sizep remain valid only until the next write operation on the stream or a call to fclose( ).

Return Values

Upon successful completion, these functions return a pointer to the object controlling the stream. Otherwise, a null pointer is returned, and errno is set to indicate the error.

Error Codes

These functions might fail if:

Item Description
[EINVAL] bufp or sizep are NULL.
[EMFILE] {FOPEN_MAX} streams are currently open in the calling process.
[ENOMEM] Memory for the stream or the buffer could not be allocated.

Examples

#include <stdio.h>

int main (void)

{

	FILE *stream;

	char *buf;

	size_t len;

	stream = open_memstream(&buf, &len);  
	
	if (stream == NULL)  

		/* handle error */;  

	fprintf(stream, "hello my world");  

	fflush(stream);  

	printf("buf=%s, len=%zu\n", buf, len);  

	fseeko(stream, 0, SEEK_SET);  

	fprintf(stream, "good-bye");  

	fclose(stream);  

	printf("buf=%s, len=%zu\n", buf, len);  

	free(buf);  

	return 0;  

} 

This program produces the following output:

buf=hello my world, len=14

buf=good-bye world, len=14