1FOPENCOOKIE(3) Linux Programmer's Manual FOPENCOOKIE(3)
2
3
4
6 fopencookie - opening a custom stream
7
9 #define _GNU_SOURCE /* See feature_test_macros(7) */
10 #include <stdio.h>
11
12 FILE *fopencookie(void *cookie, const char *mode,
13 cookie_io_functions_t io_funcs);
14
16 The fopencookie() function allows the programmer to create a custom
17 implementation for a standard I/O stream. This implementation can
18 store the stream's data at a location of its own choosing; for example,
19 fopencookie() is used to implement fmemopen(3), which provides a stream
20 interface to data that is stored in a buffer in memory.
21
22 In order to create a custom stream the programmer must:
23
24 * Implement four "hook" functions that are used internally by the
25 standard I/O library when performing I/O on the stream.
26
27 * Define a "cookie" data type, a structure that provides bookkeeping
28 information (e.g., where to store data) used by the aforementioned
29 hook functions. The standard I/O package knows nothing about the
30 contents of this cookie (thus it is typed as void * when passed to
31 fopencookie()), but automatically supplies the cookie as the first
32 argument when calling the hook functions.
33
34 * Call fopencookie() to open a new stream and associate the cookie and
35 hook functions with that stream.
36
37 The fopencookie() function serves a purpose similar to fopen(3): it
38 opens a new stream and returns a pointer to a FILE object that is used
39 to operate on that stream.
40
41 The cookie argument is a pointer to the caller's cookie structure that
42 is to be associated with the new stream. This pointer is supplied as
43 the first argument when the standard I/O library invokes any of the
44 hook functions described below.
45
46 The mode argument serves the same purpose as for fopen(3). The follow‐
47 ing modes are supported: r, w, a, r+, w+, and a+. See fopen(3) for
48 details.
49
50 The io_funcs argument is a structure that contains four fields pointing
51 to the programmer-defined hook functions that are used to implement
52 this stream. The structure is defined as follows
53
54 typedef struct {
55 cookie_read_function_t *read;
56 cookie_write_function_t *write;
57 cookie_seek_function_t *seek;
58 cookie_close_function_t *close;
59 } cookie_io_functions_t;
60
61 The four fields are as follows:
62
63 cookie_read_function_t *read
64 This function implements read operations for the stream. When
65 called, it receives three arguments:
66
67 ssize_t read(void *cookie, char *buf, size_t size);
68
69 The buf and size arguments are, respectively, a buffer into
70 which input data can be placed and the size of that buffer. As
71 its function result, the read function should return the number
72 of bytes copied into buf, 0 on end of file, or -1 on error. The
73 read function should update the stream offset appropriately.
74
75 If *read is a null pointer, then reads from the custom stream
76 always return end of file.
77
78 cookie_write_function_t *write
79 This function implements write operations for the stream. When
80 called, it receives three arguments:
81
82 ssize_t write(void *cookie, const char *buf, size_t size);
83
84 The buf and size arguments are, respectively, a buffer of data
85 to be output to the stream and the size of that buffer. As its
86 function result, the write function should return the number of
87 bytes copied from buf, or 0 on error. (The function must not
88 return a negative value.) The write function should update the
89 stream offset appropriately.
90
91 If *write is a null pointer, then output to the stream is dis‐
92 carded.
93
94 cookie_seek_function_t *seek
95 This function implements seek operations on the stream. When
96 called, it receives three arguments:
97
98 int seek(void *cookie, off64_t *offset, int whence);
99
100 The *offset argument specifies the new file offset depending on
101 which of the following three values is supplied in whence:
102
103 SEEK_SET
104 The stream offset should be set *offset bytes from the
105 start of the stream.
106
107 SEEK_CUR
108 *offset should be added to the current stream offset.
109
110 SEEK_END
111 The stream offset should be set to the size of the stream
112 plus *offset.
113
114 Before returning, the seek function should update *offset to
115 indicate the new stream offset.
116
117 As its function result, the seek function should return 0 on
118 success, and -1 on error.
119
120 If *seek is a null pointer, then it is not possible to perform
121 seek operations on the stream.
122
123 cookie_close_function_t *close
124 This function closes the stream. The hook function can do
125 things such as freeing buffers allocated for the stream. When
126 called, it receives one argument:
127
128 int close(void *cookie);
129
130 The cookie argument is the cookie that the programmer supplied
131 when calling fopencookie().
132
133 As its function result, the close function should return 0 on
134 success, and EOF on error.
135
136 If *close is NULL, then no special action is performed when the
137 stream is closed.
138
140 On success fopencookie() returns a pointer to the new stream. On
141 error, NULL is returned.
142
144 For an explanation of the terms used in this section, see
145 attributes(7).
146
147 ┌──────────────┬───────────────┬─────────┐
148 │Interface │ Attribute │ Value │
149 ├──────────────┼───────────────┼─────────┤
150 │fopencookie() │ Thread safety │ MT-Safe │
151 └──────────────┴───────────────┴─────────┘
153 This function is a nonstandard GNU extension.
154
156 The program below implements a custom stream whose functionality is
157 similar (but not identical) to that available via fmemopen(3). It
158 implements a stream whose data is stored in a memory buffer. The pro‐
159 gram writes its command-line arguments to the stream, and then seeks
160 through the stream reading two out of every five characters and writing
161 them to standard output. The following shell session demonstrates the
162 use of the program:
163
164 $ ./a.out 'hello world'
165 /he/
166 / w/
167 /d/
168 Reached end of file
169
170 Note that a more general version of the program below could be improved
171 to more robustly handle various error situations (e.g., opening a
172 stream with a cookie that already has an open stream; closing a stream
173 that has already been closed).
174
175 Program source
176
177 #define _GNU_SOURCE
178 #include <sys/types.h>
179 #include <stdio.h>
180 #include <stdlib.h>
181 #include <unistd.h>
182 #include <string.h>
183
184 #define INIT_BUF_SIZE 4
185
186 struct memfile_cookie {
187 char *buf; /* Dynamically sized buffer for data */
188 size_t allocated; /* Size of buf */
189 size_t endpos; /* Number of characters in buf */
190 off_t offset; /* Current file offset in buf */
191 };
192
193 ssize_t
194 memfile_write(void *c, const char *buf, size_t size)
195 {
196 char *new_buff;
197 struct memfile_cookie *cookie = c;
198
199 /* Buffer too small? Keep doubling size until big enough */
200
201 while (size + cookie->offset > cookie->allocated) {
202 new_buff = realloc(cookie->buf, cookie->allocated * 2);
203 if (new_buff == NULL) {
204 return -1;
205 } else {
206 cookie->allocated *= 2;
207 cookie->buf = new_buff;
208 }
209 }
210
211 memcpy(cookie->buf + cookie->offset, buf, size);
212
213 cookie->offset += size;
214 if (cookie->offset > cookie->endpos)
215 cookie->endpos = cookie->offset;
216
217 return size;
218 }
219
220 ssize_t
221 memfile_read(void *c, char *buf, size_t size)
222 {
223 ssize_t xbytes;
224 struct memfile_cookie *cookie = c;
225
226 /* Fetch minimum of bytes requested and bytes available */
227
228 xbytes = size;
229 if (cookie->offset + size > cookie->endpos)
230 xbytes = cookie->endpos - cookie->offset;
231 if (xbytes < 0) /* offset may be past endpos */
232 xbytes = 0;
233
234 memcpy(buf, cookie->buf + cookie->offset, xbytes);
235
236 cookie->offset += xbytes;
237 return xbytes;
238 }
239
240 int
241 memfile_seek(void *c, off64_t *offset, int whence)
242 {
243 off64_t new_offset;
244 struct memfile_cookie *cookie = c;
245
246 if (whence == SEEK_SET)
247 new_offset = *offset;
248 else if (whence == SEEK_END)
249 new_offset = cookie->endpos + *offset;
250 else if (whence == SEEK_CUR)
251 new_offset = cookie->offset + *offset;
252 else
253 return -1;
254
255 if (new_offset < 0)
256 return -1;
257
258 cookie->offset = new_offset;
259 *offset = new_offset;
260 return 0;
261 }
262
263 int
264 memfile_close(void *c)
265 {
266 struct memfile_cookie *cookie = c;
267
268 free(cookie->buf);
269 cookie->allocated = 0;
270 cookie->buf = NULL;
271
272 return 0;
273 }
274
275 int
276 main(int argc, char *argv[])
277 {
278 cookie_io_functions_t memfile_func = {
279 .read = memfile_read,
280 .write = memfile_write,
281 .seek = memfile_seek,
282 .close = memfile_close
283 };
284 FILE *stream;
285 struct memfile_cookie mycookie;
286 ssize_t nread;
287 long p;
288 int j;
289 char buf[1000];
290
291 /* Set up the cookie before calling fopencookie() */
292
293 mycookie.buf = malloc(INIT_BUF_SIZE);
294 if (mycookie.buf == NULL) {
295 perror("malloc");
296 exit(EXIT_FAILURE);
297 }
298
299 mycookie.allocated = INIT_BUF_SIZE;
300 mycookie.offset = 0;
301 mycookie.endpos = 0;
302
303 stream = fopencookie(&mycookie,"w+", memfile_func);
304 if (stream == NULL) {
305 perror("fopencookie");
306 exit(EXIT_FAILURE);
307 }
308
309 /* Write command-line arguments to our file */
310
311 for (j = 1; j < argc; j++)
312 if (fputs(argv[j], stream) == EOF) {
313 perror("fputs");
314 exit(EXIT_FAILURE);
315 }
316
317 /* Read two bytes out of every five, until EOF */
318
319 for (p = 0; ; p += 5) {
320 if (fseek(stream, p, SEEK_SET) == -1) {
321 perror("fseek");
322 exit(EXIT_FAILURE);
323 }
324 nread = fread(buf, 1, 2, stream);
325 if (nread == -1) {
326 perror("fread");
327 exit(EXIT_FAILURE);
328 }
329 if (nread == 0) {
330 printf("Reached end of file\n");
331 break;
332 }
333
334 printf("/%.*s/\n", nread, buf);
335 }
336
337 exit(EXIT_SUCCESS);
338 }
339
341 fclose(3), fmemopen(3), fopen(3), fseek(3)
342
344 This page is part of release 5.07 of the Linux man-pages project. A
345 description of the project, information about reporting bugs, and the
346 latest version of this page, can be found at
347 https://www.kernel.org/doc/man-pages/.
348
349
350
351Linux 2020-04-11 FOPENCOOKIE(3)