Binary Stream I/O, fseeko & EOF

Looping on while (!feof(fp)) duplicates the final record on every clean file, storing fgetc() into char spins forever on unsigned-char ARMv7 Linux, and skipping fseeko() between fwrite() and fread() corrupts update streams. You will master item-counted binary stdio, 64-bit fseeko/ftello, turnaround barriers, and 257-state EOF triage.

20 minfree previewLinux 6.12C11glibc 2.39→ module 5 lab
What you'll learn
  • Serialize and read fixed-width binary structs via item-counted fwrite()/fread() while recovering torn tail bytes.
  • Reposition 64-bit streams portably with fseeko(), ftello(), and rewind() across C11 + turnaround barriers.
  • Disambiguate short counts with feof(), ferror(), and int fgetc() without while (!feof(fp)) or 0xFF char bugs.

Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers

Three <stdio.h> bugs survive code review with alarming frequency. First, a log reader written as while (!feof(fp)) { fread(&rec, sizeof(rec), 1, fp); process(&rec); } processes the final record twice on every clean file—and loops forever if a storage EIO fault occurs! Second, a developer writes char c; while ((c = fgetc(fp)) != EOF): on x86-64 (signed char), valid binary payload byte 0xFF sign-extends to -1 and aborts early as a false EOF; cross-compiled to ARMv7 (Cortex-A7, where ABI char is unsigned char [0..255]), EOF (-1) truncates to 255, so c != -1 is always true and hangs the device at 100% CPU! Third, calling fread() immediately after fwrite() on a "w+" stream without an intervening seek or flush reads stale buffer garbage.

Writing rock-solid binary stdio code requires mastering four exact contracts: item-counted fread/fwrite return division, 64-bit fseeko/ftello update-stream turnaround barriers, post-read feof/ferror triage, and the 257-state int domain of fgetc().

note: Calling fread(recs, sizeof(rec), K, fp) is like asking a bottling machine to fill K six-packs rather than counting individual bottles — if five loose bottles remain when the tank runs dry, the machine reports zero completed six-packs.

Where it stops working: A bottling line leaves partial bottles visible on the belt, whereas fread() leaves the partial record bytes indeterminate inside your destination buffer and advances the stream position across them.

definition (Item-Counted I/O, Sticky Stream Indicators & 257-State EOF): Item-Counted Stream I/O (fread / fwrite): Unlike raw read()/write() (ssize_t bytes), fread(ptr, size, nmemb, fp) returns size_t complete items (0..nmemb). 64-Bit Stream Offsets (fseeko / ftello): Replace ISO C long (32-bit on ILP32 ARMv7) with 64-bit off_t and enforce C11 "+" update-stream turnaround synchronization. Sticky Indicators (feof, ferror) & 257-State EOF: _IO_EOF_SEEN turns on only after a read attempts to cross EOF (persisting until clearerr/rewind/fseeko), while fgetc() returns unsigned char widened to int (0..255) plus negative EOF (-1)—257 states requiring an int variable.

One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()

Inside glibc (iofread.c), fread(ptr, size, nmemb, fp) computes requested bytes R = size * nmemb (checking overflow), drains B <= R available bytes from _IO_read_ptr and underlying read(), and returns the integer quotient items_read = B / size. If a 54-byte crashed file holds three 16-byte structs (48 bytes) plus 6 torn tail bytes (B = 54), fread(out, 16, 4, fp) consumes all 54 bytes, sets _IO_EOF_SEEN on the failed attempt to reach 64 bytes, and returns 54 / 16 = 3! Passing size = 1, nmemb = 64 instead returns exact byte count 54, letting recovery code detect 54 % 16 = 6 torn bytes cleanly.

Similarly, the Pigeonhole Principle explains why char can never hold fgetc(fp): every 8-bit byte 0x00..0xFF (2^8 = 256 values) is legal inside a binary file, and EOF (-1) must be distinguishable from all 256 valid bytes (256 + 1 = 257 > 256). Narrowing 257 states into 8 bits either collides 0xFF with -1 (signed char) or loses -1 completely (unsigned char 255 != -1).

<stdio.h> InterfaceReturn Type & RangeStream State & Portability Rule
fread(p, sz, n, fp) / fwritesize_t (0..n whole items)Short count (< n) sets sticky feof(fp) or ferror(fp)
fgetc(fp) / getchar()int (0..255 or -1 EOF)Never store in char; check ch != EOF as int first
fseek(fp, long, w) / ftellint / longlong overflows at 2 GiB - 1 (EOVERFLOW) on 32-bit ARMv7
fseeko(fp, off_t, w) / ftelloint (0 ok) / 64-bit off_tClears feof; required turnaround barrier on "r+"/"w+"/"a+"
rewind(fp) / clearerr(fp)voidrewind seeks to 0 and clears both feof and ferror bits
fig_m05_l02_arch.svg — Item-counted fread() torn-tail division, C11 '+' stream…

Figure 5.2. Item-counted fread() torn-tail division, C11 '+' stream turnaround barriers, and 257-state int fgetc() safety.

step_m05_l02.svg — Drive binary loops on fread()'s item count, synchronize…step 1/4
  1. Step 1. Serialize fixed-width records verified with _Static_assert via fwrite() and track 64-bit offsets with ftello().
  2. Step 2. Insert an explicit fseeko() (or fflush() after output) before every read/write turnaround on a '+' stream.
  3. Step 3. Drive read loops with while (fread(&cur, sizeof(cur), 1, fp) == 1) rather than broken while (!feof(fp)).
  4. Step 4. Triage ferror(fp) vs feof(fp) after loop exit, and hold fgetc() in int ch so 0xFF never collides with EOF.

Figure 5.2b. Drive binary loops on fread()'s item count, synchronize '+' turnarounds with 64-bit fseeko(), and always store fgetc() in an int.

64-Bit Feature Macros & C11 Update-Stream ("+") Turnaround Rules

Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 at lines 1–2 before <stdio.h> and <stdint.h>. On any update stream ("r+", "w+", "a+"), ISO C11 §7.21.5.3 requires: (1) output (fwrite/fputs) must not be followed directly by input (fread/fgetc) without an intervening fflush() or file-positioning call (fseeko/rewind), and (2) input must not be followed directly by output without a positioning call unless input already hit EOF.

Testing Torn Tails, Turnaround Barriers, 257-State fgetc & feof Timing

Save binary_stream_eof.c below. On /tmp/ksa_m05_l02.bin ("w+be"), it writes 3 fixed 16-byte sample_rec structs (48 bytes) plus 6 torn bytes ending in 0xFF (total=54 via ftello()), executes the mandatory fseeko(fp, 0, SEEK_SET) turnaround before fread(out, 16, 4, fp) (items=3, eof=1, err=0), clears flags with clearerr(), reads all 6 torn bytes including 0xFF via int ch = fgetc(fp), proves both signed char and unsigned char narrowing bugs algebraically, and demonstrates feof(fp) == 0 right at byte 48 until a 4th read attempts to read past EOF!

learner@ksa: ~/gl-c01/m05-l02
learner@ksa:~/gl-c01/m05-l02$ bat -H 26 -H 39 -H 59 binary_stream_eof.c File: binary_stream_eof.c    #define _POSIX_C_SOURCE 200809L    #define _FILE_OFFSET_BITS 64    #include <stdint.h>    #include <stdio.h>    #include <unistd.h>        struct sample_rec {        uint32_t seq;        int32_t mv;        uint64_t ts_ns;    };    _Static_assert(sizeof(struct sample_rec) == 16, "packed by natural alignment");        int main(void) {        const char *path = "/tmp/ksa_m05_l02.bin";        FILE *fp = fopen(path, "w+be");        if (!fp) return 1;            struct sample_rec src[3] = {            {1U, 3300, 1000ULL}, {2U, 3295, 2000ULL}, {3U, 3310, 3000ULL}        };        const unsigned char torn[6] = {0xAAU, 0xBBU, 0xCCU, 0xDDU, 0xEEU, 0xFFU};        if (fwrite(src, sizeof(src[0]), 3, fp) != 3) return 1;        if (fwrite(torn, 1, sizeof(torn), fp) != sizeof(torn)) return 1;        off_t total = ftello(fp);          if (fseeko(fp, 0, SEEK_SET) != 0) return 1;        struct sample_rec out[4];        size_t items = fread(out, sizeof(out[0]), 4, fp);        int eof1 = feof(fp) ? 1 : 0;        int err1 = ferror(fp) ? 1 : 0;        printf("item_read: total=%lld items=%zu eof=%d err=%d last_mv=%d\n",               (long long)total, items, eof1, err1, (int)out[2].mv);            clearerr(fp);        int cleared_ok = (!feof(fp) && !ferror(fp)) ? 1 : 0;        if (fseeko(fp, 48, SEEK_SET) != 0) return 1;        size_t tail_bytes = 0;      unsigned int first_hex = 0U, saw_ff = 0U;        int ch;        while ((ch = fgetc(fp)) != EOF) {            if (tail_bytes == 0) first_hex = (unsigned int)ch;            if (ch == 0xFF) saw_ff = 1U;            tail_bytes++;        }        signed char x86_bug = (signed char)0xFF;        unsigned char arm_bug = (unsigned char)EOF;        int fgetc_ok = ((int)x86_bug == EOF && (int)arm_bug == 255 &&                        saw_ff == 1U);        printf("byte_tail: cleared=%d bytes=%zu hex0=%02X fgetc_257=%d\n",               cleared_ok, tail_bytes, first_hex, fgetc_ok);            if (fclose(fp) != 0) return 1;        fp = fopen(path, "w+be");        if (!fp || fwrite(src, sizeof(src[0]), 3, fp) != 3) return 1;        rewind(fp);        size_t clean_loops = 0;        struct sample_rec cur;      while (fread(&cur, sizeof(cur), 1, fp) == 1) {            clean_loops++;        }        rewind(fp);        size_t read3 = fread(out, sizeof(out[0]), 3, fp);        int eof_exact = feof(fp) ? 1 : 0;        size_t read4 = fread(&cur, sizeof(cur), 1, fp);        int eof_past = feof(fp) ? 1 : 0;            if (fclose(fp) != 0) return 1;        (void)unlink(path);            printf("eof_timing: loops=%zu r3=%zu exact=%d r4=%zu past=%d\n",               clean_loops, read3, eof_exact, read4, eof_past);        return 0;    }
  1. Insert fseeko(fp, 0, SEEK_SET) before switching from fwrite() to fread() on a w+be update stream.
  2. Store fgetc(fp) in int ch (never char) so byte 0xFF (255) stays distinct from negative EOF (-1) on both x86-64 and ARMv7.
  3. Drive loops with while (fread(&cur, sizeof(cur), 1, fp) == 1); feof(fp) stays 0 at exact EOF until a read crosses past byte 48.

Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing

Compile and run binary_stream_eof: observe items=3 (54 / 16), byte_tail recovering all 6 torn bytes including 0xFF (fgetc_257=1), and eof_timing proving exact=0 right at byte 48 before turning past=1 on the 4th read!

learner@ksa: ~/gl-c01/m05-l02
learner@ksa:~/gl-c01/m05-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror binary_stream_eof.c -o binary_stream_eoflearner@ksa:~/gl-c01/m05-l02./binary_stream_eofitem_read: total=54 items=3 eof=1 err=0 last_mv=3310byte_tail: cleared=1 bytes=6 hex0=AA fgetc_257=1eof_timing: loops=3 r3=3 exact=0 r4=0 past=1learner@ksa:~/gl-c01/m05-l02test ! -e /tmp/ksa_m05_l02.bin && rm -f binary_stream_eoflearner@ksa:~/gl-c01/m05-l02

Why Byte-Exact Tail Recovery Needs size = 1 or ftello()

Notice what happened when fread(out, 16, 4, fp) hit the 54-byte torn file: it returned 3 items, yet the stream offset advanced to 54 (6 partial bytes consumed into out[3] without completing item 4)! Whenever your framing protocol must detect and reject a partial trailing struct (rather than treating 3 items + EOF as a clean 48-byte file), read with size = 1, nmemb = sizeof(rec) and check got == 0 (clean EOF) versus 0 < got < sizeof(rec) (corrupt torn tail!).

Guided Practice: Detecting a Torn Struct Tail with size = 1

Rewrite the while (fread(&cur, sizeof(cur), 1, fp) == 1) loop so it distinguishes clean EOF from a 6-byte torn trailing record without extra fstat() syscalls:

  1. Step 1 (Switch to byte-granularity fread): Call size_t nb = fread(&cur, 1U, sizeof(cur), fp); on each iteration; when nb == sizeof(cur), a complete struct arrived.
  2. Step 2 (Triage nb < sizeof(cur)): Check if (ferror(fp)) first (I/O error), else if nb == 0 (clean EOF on a record boundary!), else (0 < nb < sizeof(cur): report a torn trailing record of nb bytes!).

Independent Practice: In-Place Binary Record Patcher on "r+be"

Write a C11 program patch_record.c (_FILE_OFFSET_BITS=64, -Wall -Wextra -Werror) that writes 5 struct sample_rec records (80 bytes), reopens the file with "r+be", scans forward via fread() until finding seq == 3U, executes the mandatory read-to-write fseeko(fp, -(off_t)sizeof(struct sample_rec), SEEK_CUR) turnaround barrier, overwrites record 3's mv field via fwrite(), executes a write-to-read turnaround, and verifies all 5 records in order!

Common Production Pitfalls

warning: Symptom: A binary parser written as while (!feof(fp)) { fread(&rec, sizeof(rec), 1, fp); emit(&rec); } emits the final record twice on every file and hangs infinitely on read errors (EIO). Root Cause: feof(fp) turns nonzero only after a read attempts to cross EOF, and never turns on when ferror(fp) halts input. Fix: Loop on while (fread(&rec, sizeof(rec), 1, fp) == 1) and test ferror(fp) vs feof(fp) once after the loop exits.

warning: Symptom: Calling fwrite(&hdr, sizeof(hdr), 1, fp) followed immediately by fread(&rec, sizeof(rec), 1, fp) on a "w+" or "r+" stream returns stale or corrupted bytes. Root Cause: ISO C11 requires an explicit flush or positioning call when switching between output and input on an update ("+") stream so glibc synchronizes _IO_write_ptr and _IO_read_ptr. Fix: Insert fseeko(fp, target_off, SEEK_SET) (or fseeko(fp, 0, SEEK_CUR)) at every read/write turnaround.

Knowledge Check

quiz · 1 of 4

A file contains 38 bytes. You open it at offset 0 and call size_t n = fread(recs, 16, 4, fp);. What does fread() return, and what are feof(fp) and ferror(fp)?

quiz · 2 of 4

Why should portable Linux C11 code prefer fseeko() and ftello() (under _FILE_OFFSET_BITS=64) over classic ISO C fseek() and ftell()?

quiz · 3 of 4

(Review from earlier lesson) Suppose you truncate an open stream's backing file via fflush(fp); ftruncate(fileno(fp), 48);. Why must you still call rewind(fp) (or fseeko(fp, 0, SEEK_SET)) before reading from byte 0?

quiz · 4 of 4

A developer writes char c; while ((c = fgetc(fp)) != EOF) on x86-64 Linux, passes ASCII tests, and cross-compiles for 32-bit ARMv7 (Cortex-A7) Linux. What happens on each target when reading a binary file containing byte 0xFF?

Key takeaways

  • fread() and fwrite() return counts of complete items (0..nmemb); use size = 1 for exact byte counts or size = sizeof(struct) for aligned fixed records.
  • fgetc() and getchar() return 257 int states (0..255 plus (int)-1 EOF); narrowing into char causes 0xFF false EOF on x86-64 and infinite loops on unsigned-char ARMv7.
  • Prefer 64-bit fseeko() and ftello() (off_t), and remember rewind(fp) resets both offset 0 and sticky feof/ferror flags.
  • On update ("+") streams, always insert fseeko() (or fflush() after writes) when switching between fwrite() and fread().
  • Drive read loops with while (fread(...) == 1) rather than while (!feof(fp)), then inspect ferror(fp) vs feof(fp) once after termination.
  • Next, we complete Module 5 by building truncation-safe snprintf() formatters (PRIu64, %zu) and fault-isolated fgets() + strtol() line parsers.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure