Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.14 Memory Streams 171


trying to create second temp file...
Segmentation fault
The difference in behavior comes from the way the two template strings are
declared. For the first template, the name is allocated on the stack, because we use an
array variable. For the second name, however, we use a pointer.Inthis case, only the
memory for the pointer itself resides on the stack; the compiler arranges for the string to
be stored in the read-only segment of the executable. When themkstempfunction tries
to modify the string, a segmentation fault occurs.

5.14 MemoryStreams


As we’ve seen, the standardI/O library buffers data in memory, so operations such as
character-at-a-time I/O and line-at-a-time I/O aremoreefficient. We’ve also seen that
we can provide our own buffer for the library to use by callingsetbuforsetvbuf.In
Version 4, the Single UNIX Specification added support formemory streams.These are
standardI/O streams for which thereare nounderlying files, although they arestill
accessed withFILEpointers. All I/O is done by transferring bytes to and from buffers
in main memory.As we shall see, even though these streams look like file streams,
several features make them moresuited for manipulating character strings.
Three functions areavailable to create memory streams. The first isfmemopen.
#include <stdio.h>
FILE *fmemopen(void *restrictbuf,size_t size,
const char *restricttype);
Returns: stream pointer if OK,NULLon error
Thefmemopenfunction allows the caller to provide a buffer to be used for the memory
stream: thebufargument points to the beginning of the buffer and thesizeargument
specifies the size of the buffer in bytes. If thebufargument is null, then thefmemopen
function allocates a buffer ofsizebytes. In this case, the buffer will be freed when the
stream is closed.
Thetypeargument controls how the stream can be used. The possible values for
typearesummarized in Figure5.14.

type Description
rorrb open for reading
worwb open for writing
aorab append; open for writing at first null byte
r+orr+borrb+ open for reading and writing
w+orw+borwb+ truncate to 0 length and open for reading and writing
a+ora+borab+ append; open for reading and writing at first null byte

Figure 5.14 Thetypeargument for opening a memory stream

Note that these values correspond to the ones for file-based standardI/O streams, but
thereare some subtle differences. First, whenever a memory stream is opened for
Free download pdf