Node:String Streams, Next:Obstack Streams, Up:Other Kinds of Streams
The fmemopen
and open_memstream
functions allow you to do
I/O to a string or memory buffer. These facilities are declared in
stdio.h
.
FILE * fmemopen (void *buf, size_t size, const char *opentype) | Function |
This function opens a stream that allows the access specified by the
opentype argument, that reads from or writes to the buffer specified
by the argument buf. This array must be at least size bytes long.
If you specify a null pointer as the buf argument, The argument opentype is the same as in When a stream open for writing is flushed or closed, a null character (zero byte) is written at the end of the buffer if it fits. You should add an extra byte to the size argument to account for this. Attempts to write more than size bytes to the buffer result in an error. For a stream open for reading, null characters (zero bytes) in the buffer do not count as "end of file". Read operations indicate end of file only when the file position advances past size bytes. So, if you want to read characters from a null-terminated string, you should supply the length of the string as the size argument. |
Here is an example of using fmemopen
to create a stream for
reading from a string:
#include <stdio.h> static char buffer[] = "foobar"; int main (void) { int ch; FILE *stream; stream = fmemopen (buffer, strlen (buffer), "r"); while ((ch = fgetc (stream)) != EOF) printf ("Got %c\n", ch); fclose (stream); return 0; }
This program produces the following output:
Got f Got o Got o Got b Got a Got r
FILE * open_memstream (char **ptr, size_t *sizeloc) | Function |
This function opens a stream for writing to a buffer. The buffer is
allocated dynamically (as with malloc ; see Unconstrained Allocation) and grown as necessary.
When the stream is closed with A null character is written at the end of the buffer. This null character is not included in the size value stored at sizeloc. You can move the stream's file position with |
Here is an example of using open_memstream
:
#include <stdio.h> int main (void) { char *bp; size_t size; FILE *stream; stream = open_memstream (&bp, &size); fprintf (stream, "hello"); fflush (stream); printf ("buf = `%s', size = %d\n", bp, size); fprintf (stream, ", world"); fclose (stream); printf ("buf = `%s', size = %d\n", bp, size); return 0; }
This program produces the following output:
buf = `hello', size = 5 buf = `hello, world', size = 12