Standard I/O Streams & fopen Modes
Emitting thousands of tiny telemetry records via raw write() syscalls burns microseconds in Ring 3-to-Ring 0 trap overhead, while naive fopen("w+") omits O_CLOEXEC and O_EXCL protections. You will dissect glibc FILE control blocks, benchmark buffered syscall amortization, map fopen() modes to openat() flags, and test open_memstream().
What you'll learn
- Analyze how
glibcFILEcontrol blocks amortize Ring 3-to-Ring 0 syscall traps above raw integer file descriptors. - Translate every C11 and
glibcfopen()mode string (b,e,x) to its exactopenat()kernel flag bitmask. - Verify
stdin/stdout/stderrdescriptor bindings,open_memstream()buffers, and checkedfclose()error handling.
Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races
Suppose a high-rate telemetry collector formats 4,096 four-byte voltage samples per batch and emits each sample with write(fd, &sample, 4). Even before touching non-volatile media, executing 4,096 synchronous syscall / svc #0 privilege switches burns roughly 4,096 * 200 ns = ~820 us in pure CPU trap overhead! Switching blindly to ISO C fopen(path, "w+"), however, introduces two new production hazards if you do not know what glibc passes to the kernel: plain "w+" omits O_CLOEXEC (leaking descriptors across execve()) and omits O_EXCL (silently truncating an existing file), while ignoring fclose(fp)'s return value drops deferred ENOSPC flush errors!
High-throughput, leak-free stream I/O requires understanding how glibc's user-space FILE control block batches transfers above raw integer descriptors, and how glibc mode suffixes ("e" and "x") forward kernel safety flags straight into openat().
note: Using raw syscalls for tiny writes is like carrying individual parcels across a guarded border checkpoint one by one, whereas a stdio FILE stream packs parcels into a user-space crate and crosses the border only when the crate fills.
Where it stops working: A physical crate sitting in your warehouse survives a building power cut, whereas bytes held inside a user-space FILE buffer vanish if the process crashes or calls _exit() before flushing.
definition (Standard I/O Stream (FILE), Mode Extensions & Memory Streams): Standard I/O Stream (FILE): Introduced by Mike Lesk and Dennis Ritchie in the Portable I/O Library (<stdio.h>), FILE (struct _IO_FILE in glibc) is an opaque Ring 3 control block wrapping an underlying _fileno descriptor with user-space _IO_read_ptr/_IO_write_ptr heap buffers, an internal mutex lock, and sticky EOF/error bits. glibc Mode Extensions ("e", "x"): Append O_CLOEXEC ("e") and O_EXCL ("x") to the initial openat() syscall. Memory Streams (open_memstream, fmemopen): Standardized in POSIX.1-2008 to bind FILE * virtual-function tables directly onto heap or caller RAM (fileno() == -1, EBADF).
One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math
Inside glibc (libio/bits/types/struct_FILE.h), writing s bytes via fwrite() or fputs() checks whether _IO_write_end - _IO_write_ptr >= s under the stream's internal flockfile lock: when room remains inside the 4,096- or 8,192-byte (BUFSIZ) heap buffer, glibc executes a pure Ring 3 memcpy() and advances _IO_write_ptr += s with zero syscalls. For N records of s bytes buffered in capacity B bytes, kernel write() traps drop from N to N_syscalls = ceil((N * s) / B). Streaming N = 4,096 one-byte writes through an 8,192-byte FILE buffer issues 1 write() syscall on fclose() instead of 4,096 traps—a 4,096x reduction in Ring 0 transitions!
fopen() Mode String | Exact openat() Kernel Flags | Missing Target | Existing Target | Stream Capabilities | ||
|---|---|---|---|---|---|---|
"r" / "rb" | O_RDONLY | NULL (ENOENT) | Preserved | Read-only from 0 ("b" is a POSIX no-op) | ||
"r+" / "r+b" | O_RDWR | NULL (ENOENT) | Preserved | Read/write update from 0 | ||
"w" / "w+" | O_WRONLY / O_RDWR `\ | O_CREAT \ | O_TRUNC` | Created (0666 & ~umask) | Truncated to 0 | Write or read/write from 0 |
"a" / "a+" | O_WRONLY / O_RDWR `\ | O_CREAT \ | O_APPEND` | Created (0666 & ~umask) | Preserved | Reads at 0 ("a+"); all writes jump to EOF |
"...e" ("re", "w+e") | Base flags `\ | O_CLOEXEC` | Per base mode | Per base mode | Sets FD_CLOEXEC atomically at open | |
"wxe" / "w+xe" | "w"/"w+" `\ | O_EXCL \ | O_CLOEXEC` | Created atomically | Fails NULL (EEXIST) | Race-free + leak-free exclusive creation |
Figure 5.1. User-space glibc struct _IO_FILE state, open_memstream() vtables, and exact fopen() mode-to-openat() flag translations.
- Step 1. Open streams with glibc 'e' (O_CLOEXEC) and 'x' (O_EXCL) suffixes inside a single atomic openat() syscall.
- Step 2. Accumulate small fputc() and fwrite() records inside the 8 KiB Ring 3 _IO_FILE heap buffer with zero traps.
- Step 3. Drain full buffers via amortized block write() syscalls, cutting mode-switch overhead by >1,000x.
- Step 4. Verify fclose(fp) == 0 on every writable stream so final flush ENOSPC or EIO faults are never lost.
Figure 5.1b. Append glibc 'e' and 'x' safety suffixes on fopen(), batch tiny records in Ring 3 heap RAM, and always check fclose(fp) == 0.
Stream Headers, Checked fclose() & open_memstream()
Define #define _POSIX_C_SOURCE 200809L before <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> so fileno(), open_memstream(), and CLOCK_MONOTONIC are declared cleanly. Every C process starts with stdin (0), stdout (1), and stderr (2) pre-opened. Calling fclose(fp) flushes buffered output via write(), closes _fileno, and frees fp, returning 0 on success or EOF (-1) if that final flush or close() hit ENOSPC/EIO—always check if (fclose(fp) != 0) on writable streams!
Probing fopen Kernel Flags, open_memstream & Amortization Speedup
Save fopen_modes_probe.c below. It verifies fileno() on stdin/stdout/stderr (0,1,2), confirms "w+e"/"w+xe"/"a+e"/"rbe" translate to exact O_ACCMODE, O_APPEND, FD_CLOEXEC, and O_EXCL (EEXIST) kernel flags, exercises an in-memory open_memstream(&mbuf, &msz) stream (fileno(mfp) == -1 && errno == EBADF), and benchmarks 2,048 one-byte raw write() traps against 2,048 buffered fputc() calls with CLOCK_MONOTONIC!
learner@ksa:~/gl-c01/m05-l01$ bat -H 25 -H 65 -H 81 fopen_modes_probe.c File: fopen_modes_probe.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> static uint64_t diff_ns(struct timespec a, struct timespec b) { return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + (uint64_t)(b.tv_nsec - a.tv_nsec); } int main(void) { const char *path = "/tmp/ksa_m05_l01.log"; (void)unlink(path); printf("std_streams: in=%d out=%d err=%d\n", fileno(stdin), fileno(stdout), fileno(stderr)); FILE *fp0 = fopen(path, "w+e"); if (!fp0) return 1; int fd0 = fileno(fp0); int wpe_ok = ((fcntl(fd0, F_GETFL) & O_ACCMODE) == O_RDWR) && ((fcntl(fd0, F_GETFD) & FD_CLOEXEC) != 0); if (fclose(fp0) != 0) return 1; (void)unlink(path); FILE *fp1 = fopen(path, "w+xe"); if (!fp1) return 1; int fd1 = fileno(fp1); int fl1 = fcntl(fd1, F_GETFL); int clo1 = (fcntl(fd1, F_GETFD) & FD_CLOEXEC) ? 1 : 0; if (fputs("BOOT\n", fp1) < 0) return 1; errno = 0; FILE *dup_wx = fopen(path, "wxe"); int wx_eexist = (dup_wx == NULL && errno == EEXIST) ? 1 : 0; if (dup_wx) (void)fclose(dup_wx); if (fclose(fp1) != 0) return 1; const char *acc1 = ((fl1 & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER"; printf("mode_wplus_xe: wpe_ok=%d acc=%s append=%d cloexec=%d wx=%d\n", wpe_ok, acc1, (fl1 & O_APPEND) ? 1 : 0, clo1, wx_eexist); FILE *fp2 = fopen(path, "a+e"); if (!fp2) return 1; int fd2 = fileno(fp2); int fl2 = fcntl(fd2, F_GETFL); int clo2 = (fcntl(fd2, F_GETFD) & FD_CLOEXEC) ? 1 : 0; if (fputs("READY\n", fp2) < 0 || fclose(fp2) != 0) return 1; FILE *fp3 = fopen(path, "rbe"); if (!fp3) return 1; struct stat st; int rbe_ok = (fstat(fileno(fp3), &st) == 0 && (fcntl(fileno(fp3), F_GETFL) & O_ACCMODE) == O_RDONLY); if (fclose(fp3) != 0 || !rbe_ok) return 1; (void)unlink(path); char *mbuf = NULL; size_t msz = 0U; FILE *mfp = open_memstream(&mbuf, &msz); if (!mfp) return 1; errno = 0; int mem_no_fd = (fileno(mfp) == -1 && errno == EBADF); fprintf(mfp, "hdr=%u", 42U); if (fclose(mfp) != 0) { free(mbuf); return 1; } int mem_ok = (mem_no_fd && msz == 6U && strcmp(mbuf, "hdr=42") == 0); free(mbuf); struct timespec t0, t1, t2; int bfd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (bfd < 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < 2048; i++) { if (write(bfd, "x", 1U) != 1) return 1; } clock_gettime(CLOCK_MONOTONIC, &t1); (void)close(bfd); FILE *bfp = fopen(path, "we"); if (!bfp) return 1; for (int i = 0; i < 2048; i++) { if (fputc('x', bfp) == EOF) return 1; } if (fclose(bfp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t2); (void)unlink(path); int faster = (diff_ns(t0, t1) > diff_ns(t1, t2)) ? 1 : 0; const char *acc2 = ((fl2 & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER"; printf("mode_aplus_e: acc=%s append=%d cloexec=%d bytes=%lld " "mem=%d buf_faster=%d\n", acc2, (fl2 & O_APPEND) ? 1 : 0, clo2, (long long)st.st_size, mem_ok, faster); return 0; }- Mode w+xe maps to O_RDWR | O_CREAT | O_TRUNC | O_EXCL | O_CLOEXEC inside a single atomic openat() syscall.
- open_memstream() backs a FILE * with dynamically growing heap RAM; fileno() returns -1 with EBADF because no kernel fd exists.
- 2,048 fputc() calls copy bytes in Ring 3 RAM and emit a single write() syscall on fclose(), beating 2,048 raw write() traps.
Verifying Stream Flags, Memory Streams & Amortization Speedup
Compile and execute fopen_modes_probe: confirm std_streams (0, 1, 2), "w+xe" (O_RDWR, FD_CLOEXEC, wx=1), "a+e" (11 concatenated bytes "BOOT\nREADY\n"), mem=1, and buf_faster=1 (2,048 buffered fputc() calls outperforming 2,048 raw write() syscalls!).
learner@ksa:~/gl-c01/m05-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror fopen_modes_probe.c -o fopen_modes_probelearner@ksa:~/gl-c01/m05-l01./fopen_modes_probestd_streams: in=0 out=1 err=2mode_wplus_xe: wpe_ok=1 acc=O_RDWR append=0 cloexec=1 wx=1mode_aplus_e: acc=O_RDWR append=1 cloexec=1 bytes=11 mem=1 buf_faster=1learner@ksa:~/gl-c01/m05-l01test ! -e /tmp/ksa_m05_l01.log && rm -f fopen_modes_probelearner@ksa:~/gl-c01/m05-l01Inside glibc fopen(), Buffer Flush & open_memstream()
When fopen(path, "w+xe") executed, glibc allocated struct _IO_FILE on the heap and called openat(AT_FDCWD, path, O_RDWR|O_CREAT|O_TRUNC|O_EXCL|O_CLOEXEC, 0666). During the 2,048-byte benchmark, fputc() incremented _IO_write_ptr inside user RAM 2,048 times and issued a single write(fd, buf, 2048) syscall inside fclose(bfp), whereas raw write(bfd, "x", 1) crossed into Ring 0 2,048 separate times!
Guided Practice: Auditing fopen Mode Strings for strace Verification
Predict the exact openat() flag mask printed by strace -e trace=openat for each of the following three calls before testing them in a 15-line C snippet:
- Step 1 (Map base C11 characters): Translate
"r+","w", and"a+"into theirO_ACCMODE(O_RDWR,O_WRONLY,O_RDWR) plusO_CREAT/O_TRUNC/O_APPENDflags. - Step 2 (Layer
glibcsafety suffixes): Add"e"and"x"("r+e","wxe","a+be") and verify understracethat"b"changes zero kernel flags while"e"and"x"addO_CLOEXECandO_EXCL.
Independent Practice: Zero-File fmemopen() & open_memstream() Unit Test
Write a C11 test memstream_roundtrip.c (-std=c11 -Wall -Wextra -Werror) containing a serializer int write_kv(FILE *out, const char *k, int v) and reader int read_kv(FILE *in, char *k_out, int *v_out). Test both functions purely in RAM—serializing into open_memstream(&buf, &len) and parsing back via fmemopen(buf, len, "r")—and verify under strace -e trace=openat that zero scratch files are opened after dynamic loader startup!
Common Production Pitfalls
warning: Symptom: A multithreaded service opens configuration streams via fopen(path, "w+") and leaks open descriptors across fork() + execve() into child processes, or clobbers files created concurrently. Root Cause: Standard C "w+" omits O_CLOEXEC and O_EXCL. Fix: Append glibc's "e" modifier ("re", "w+e", "ae") on all Linux daemon streams, and add "x" ("wxe", "w+xe") for atomic exclusive file creation.
warning: Symptom: Small fputs() writes return >= 0 without error, yet disk-full (ENOSPC) corruption goes completely undetected because the caller wrote fclose(fp); without checking its return code! Root Cause: Buffered writes stay in Ring 3 RAM until the buffer fills or fclose(fp) flushes remaining bytes via write(), reporting ENOSPC or EIO only through fclose() returning EOF (-1). Fix: Always treat if (fclose(fp) != 0) on writable streams as an I/O failure.
Knowledge Check
Key takeaways
glibcFILEstreams wrap integer file descriptors with user-space_IO_read_ptr/_IO_write_ptrbuffers and sticky status bits to amortize Ring 3-to-Ring 0 syscall overhead.- Every hosted C process starts with pre-opened
stdin(0),stdout(1), andstderr(2) streams in<stdio.h>. fopen()modes"r","r+","w","w+","a", and"a+"map deterministically toO_RDONLY/O_RDWR/O_WRONLYplusO_CREAT,O_TRUNC, orO_APPEND, while"b"is a POSIX no-op.- Linux
glibcextensions"e"(O_CLOEXEC) and"x"(O_EXCL) close descriptor-leak and creation-race windows inside the initialopenat(), andfclose(fp)must always be checked on writable streams. - POSIX.1-2008
open_memstream()andfmemopen()backFILE *streams directly with RAM (fileno() == -1,EBADF). - Next, we serialize fixed-width binary structs over
FILE *streams using item-countedfread()/fwrite(), 64-bitfseeko()/ftello(), stickyfeof()/ferror()triage, and 257-stateintfgetc().