Next: Hook Functions, Up: Custom Streams [Contents][Index]
Inside every custom stream is a special object called the cookie.
This is an object supplied by you which records where to fetch or store
the data read or written. It is up to you to define a data type to use
for the cookie. The stream functions in the library never refer
directly to its contents, and they don’t even know what the type is;
they record its address with type void *
.
To implement a custom stream, you must specify how to fetch or store the data in the specified place. You do this by defining hook functions to read, write, change “file position”, and close the stream. All four of these functions will be passed the stream’s cookie so they can tell where to fetch or store the data. The library functions don’t know what’s inside the cookie, but your functions will know.
When you create a custom stream, you must specify the cookie pointer,
and also the four hook functions stored in a structure of type
cookie_io_functions_t
.
These facilities are declared in stdio.h.
This is a structure type that holds the functions that define the communications protocol between the stream and its cookie. It has the following members:
cookie_read_function_t *read
This is the function that reads data from the cookie. If the value is a
null pointer instead of a function, then read operations on this stream
always return EOF
.
cookie_write_function_t *write
This is the function that writes data to the cookie. If the value is a null pointer instead of a function, then data written to the stream is discarded.
cookie_seek_function_t *seek
This is the function that performs the equivalent of file positioning on
the cookie. If the value is a null pointer instead of a function, calls
to fseek
or fseeko
on this stream can only seek to
locations within the buffer; any attempt to seek outside the buffer will
return an ESPIPE
error.
cookie_close_function_t *close
This function performs any appropriate cleanup on the cookie when closing the stream. If the value is a null pointer instead of a function, nothing special is done to close the cookie when the stream is closed.
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem lock | See POSIX Safety Concepts.
This function actually creates the stream for communicating with the
cookie using the functions in the io-functions argument.
The opentype argument is interpreted as for fopen
;
see Opening Streams. (But note that the “truncate on
open” option is ignored.) The new stream is fully buffered.
The fopencookie
function returns the newly created stream, or a null
pointer in case of an error.
Next: Hook Functions, Up: Custom Streams [Contents][Index]