fopencookie(3)
π fopencookie(3) β the girlies are opening custom streams π
okay so bestie, this is fopencookie(3), sitting pretty in section 3 (Library Functions Manual) of the Unix manual. And no cap, this one is the glow-up function: it's how you build your own I/O stream from scratch. Let's get into it π¦
β¨ NAME β¨
fopencookie β open a custom stream π
π LIBRARY π
Standard C library (libc, -lc) β the classic, the icon, the one you already link against π
π«Ά SYNOPSIS π«Ά
#define _GNU_SOURCE /* See feature_test_macros(7) */
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
FILE *fopencookie(void *restrict cookie, const char *restrict mode,
cookie_io_functions_t io_funcs);
πΈ DESCRIPTION πΈ
So here's the tea β: fopencookie() lets the programmer build a custom implementation for a standard I/O stream. And like. not just a little custom. The implementation can stash the stream's data wherever it wants. That's the whole point, bestie. For example, fopencookie() is literally what's used to implement fmemopen(3) β you know, the thing that gives you a stream interface over data sitting in a buffer in memory. Iconic behaviour, honestly π
To create a custom stream, the programmer must (no skipping steps, this isn't optional):
- Implement four "hook" functions that get used internally by the standard I/O library whenever it's doing I/O on the stream. Four. Count 'em π₯
- Define a "cookie" data type β a structure that carries the bookkeeping info (like, where to store the data) that those hook functions need. And here's the wild part: the standard I/O package knows nothing about what's inside this cookie (that's why it's typed as
void *when you hand it tofopencookie()), but it automatically supplies the cookie as the first argument whenever it calls the hook functions. She provides β¨ - Call
fopencookie()to open a new stream and marry the cookie + hook functions to that stream π
fopencookie() serves a purpose super similar to fopen(3): it opens a new stream and hands you back a pointer to a FILE object that you use to operate on that stream.
The cookie argument is a pointer to your cookie structure β the one that's getting associated with the new stream. This pointer is what gets supplied as the first argument every time the standard I/O library invokes any of the hook functions described down below π
The mode argument does the exact same job it does for fopen(3). The following modes are supported: r, w, a, r+, w+, and a+. Go see fopen(3) for the details, bestie π
The io_funcs argument is a structure holding four fields, each one pointing at a programmer-defined hook function that implements this stream. The structure is defined like this:
typedef struct {
cookie_read_function_t *read;
cookie_write_function_t *write;
cookie_seek_function_t *seek;
cookie_close_function_t *close;
} cookie_io_functions_t;
And the four fields, one at a time, because we're thorough like that:
π cookie_read_function_t *read
This one implements read operations for the stream. When it gets called, it receives three arguments:
ssize_t read(void *cookie, char *buf, size_t size);
The buf and size arguments are, respectively, a buffer that input data can be plopped into, and the size of that buffer. As its function result, the read function should return the number of bytes copied into buf, 0 on end of file, or -1 on error. Also the read function should update the stream offset appropriately, don't forget that part π
If *read is a null pointer, then reads from the custom stream always return end of file. Ghosted, basically π
π cookie_write_function_t *write
This one implements write operations for the stream. When it gets called, it receives three arguments:
ssize_t write(void *cookie, const char *buf, size_t size);
The buf and size arguments are, respectively, a buffer of data to be output to the stream, and the size of that buffer. As its function result, the write function should return the number of bytes copied from buf, or 0 on error. (And listen β the function must not return a negative value. That's the rule.) The write function should update the stream offset appropriately too, same as read π«Ά
If *write is a null pointer, then output to the stream is just discarded. Gone. Poof π¬οΈ
π cookie_seek_function_t *seek
This one implements seek operations on the stream. When it gets called, it receives three arguments:
int seek(void *cookie, off_t *offset, int whence);
The *offset argument specifies the new file offset, and what it means depends on which of these three values shows up in whence:
SEEK_SETβ the stream offset should be set*offsetbytes from the start of the stream.SEEK_CURβ*offsetshould be added to the current stream offset.SEEK_ENDβ the stream offset should be set to the size of the stream plus*offset.
Before it returns, the seek function should update *offset to indicate the new stream offset. And as its function result, the seek function should return 0 on success, and -1 on error.
If *seek is a null pointer, then it is simply not possible to perform seek operations on the stream. No seeking, no sliding π
π cookie_close_function_t *close
This one closes the stream. The hook function can do stuff like freeing buffers that were allocated for the stream β cleanup era π§Ή When it gets called, it receives one argument:
int close(void *cookie);
The cookie argument is the cookie that the programmer supplied when calling fopencookie().
As its function result, the close function should return 0 on success, and EOF on error.
If *close is NULL, then no special action is performed when the stream is closed. It just. closes. Casually πΈ
π RETURN VALUE π
On success, fopencookie() returns a pointer to the new stream. On error, NULL is returned. Simple as that, bestie π
β ATTRIBUTES β
For an explanation of the terms used in this section, go peek at attributes(7). And here's the deets:
fopencookie()β Thread safety:MT-Safeπ
π STANDARDS π
GNU. That's it, that's the whole vibe π
π EXAMPLES π
Okay bestie, here's where it gets good. The program below implements a custom stream whose functionality is similar (but not identical) to that available via fmemopen(3). It implements a stream whose data is stored in a memory buffer. The program writes its command-line arguments to the stream, and then seeks through the stream reading two out of every five characters and writing them to standard output. The following shell session demonstrates the use of the program:
$ ./a.out 'hello world'
/he/
/ w/
/d/
Reached end of file
ngl, a more general version of the program below could be improved to more robustly handle various error situations (e.g., opening a stream with a cookie that already has an open stream; closing a stream that has already been closed). So like, it's a vibe, not a production-ready baddie π
πΈ Program source πΈ
Sleepover time, here's the whole thing, every line, no cap:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define INIT_BUF_SIZE 4
struct memfile_cookie {
char *buf; /* Dynamically sized buffer for data */
size_t allocated; /* Size of buf */
size_t endpos; /* Number of characters in buf */
off_t offset; /* Current file offset in buf */
};
static ssize_t
memfile_write(void *c, const char *buf, size_t size)
{
char *new_buff;
struct memfile_cookie *cookie = c;
/* Buffer too small? Keep doubling size until big enough. */
while (size + cookie->offset > cookie->allocated) {
new_buff = realloc(cookie->buf, cookie->allocated * 2);
if (new_buff == NULL)
return -1;
cookie->allocated *= 2;
cookie->buf = new_buff;
}
memcpy(cookie->buf + cookie->offset, buf, size);
cookie->offset += size;
if (cookie->offset > cookie->endpos)
cookie->endpos = cookie->offset;
return size;
}
static ssize_t
memfile_read(void *c, char *buf, size_t size)
{
ssize_t xbytes;
struct memfile_cookie *cookie = c;
/* Fetch minimum of bytes requested and bytes available. */
xbytes = size;
if (cookie->offset + size > cookie->endpos)
xbytes = cookie->endpos - cookie->offset;
if (xbytes < 0) /* offset may be past endpos */
xbytes = 0;
memcpy(buf, cookie->buf + cookie->offset, xbytes);
cookie->offset += xbytes;
return xbytes;
}
static int
memfile_seek(void *c, off_t *offset, int whence)
{
off_t new_offset;
struct memfile_cookie *cookie = c;
if (whence == SEEK_SET)
new_offset = *offset;
else if (whence == SEEK_END)
new_offset = cookie->endpos + *offset;
else if (whence == SEEK_CUR)
new_offset = cookie->offset + *offset;
else
return -1;
if (new_offset < 0)
return -1;
cookie->offset = new_offset;
*offset = new_offset;
return 0;
}
static int
memfile_close(void *c)
{
struct memfile_cookie *cookie = c;
free(cookie->buf);
cookie->allocated = 0;
cookie->buf = NULL;
return 0;
}
int
main(int argc, char *argv[])
{
cookie_io_functions_t memfile_func = {
.read = memfile_read,
.write = memfile_write,
.seek = memfile_seek,
.close = memfile_close
};
FILE *stream;
struct memfile_cookie mycookie;
size_t nread;
char buf[1000];
/* Set up the cookie before calling fopencookie(). */
mycookie.buf = malloc(INIT_BUF_SIZE);
if (mycookie.buf == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
mycookie.allocated = INIT_BUF_SIZE;
mycookie.offset = 0;
mycookie.endpos = 0;
stream = fopencookie(&mycookie, "w+", memfile_func);
if (stream == NULL) {
perror("fopencookie");
exit(EXIT_FAILURE);
}
/* Write command-line arguments to our file. */
for (size_t j = 1; j < argc; j++)
if (fputs(argv[j], stream) == EOF) {
perror("fputs");
exit(EXIT_FAILURE);
}
/* Read two bytes out of every five, until EOF. */
for (long p = 0; ; p += 5) {
if (fseek(stream, p, SEEK_SET) == -1) {
perror("fseek");
exit(EXIT_FAILURE);
}
nread = fread(buf, 1, 2, stream);
if (nread == 0) {
if (ferror(stream) != 0) {
fprintf(stderr, "fread failed\n");
exit(EXIT_FAILURE);
}
printf("Reached end of file\n");
break;
}
printf("/%.*s/\n", (int) nread, buf);
}
free(mycookie.buf);
exit(EXIT_SUCCESS);
}
π«Ά NOTES π«Ά
fr fr, listen up, this one's a portability thing and it's lowkey important:
_FILE_OFFSET_BITS should be defined to be 64 in code that uses non-null seek or that takes the address of fopencookie, if the code is intended to be portable to traditional 32-bit x86 and ARM platforms where off_t's width defaults to 32 bits.
π
heads up bestie: skip that define and your off_t is gonna be a whole 32 bits wide on those platforms, which is not the vibe you want for file offsets.
π SEE ALSO π
The girlies you should also be reading, periodt:
okay that's the whole page, you made it, I'm so proud of you π₯Ήπ«Ά this icon of a manual page is from Linux man-pages 6.20, dated 2025-09-21 β go off, upstream maintainers, you ate π β¨
π¦ where this page comes from
- arch rolling: man-pages 6.20-1 Β· BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- π the page's license: Linux-man-pages-copyleft
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms