Binary I/O & File Positioning in C
Binary files trade human readability for exactness: fopen with "rb"/"wb" disables newline translation, fread(ptr, size, n, fp) pulls n items returning the count actually read, and fwrite mirrors it. Partial counts signal EOF or error mid-stream — always compare against n.
fseek(fp, offset, SEEK_SET/SEEK_CUR/SEEK_END) repositions, ftell reports the current byte offset, and rewind(fp) returns to start (clearing error flags too). Random access plus binary layout equals databases, indexes, and save files — with endianness and padding caveats carried over from memory layout.
Binary modes
"rb"/"wb" pass bytes through untouched — mandatory on Windows where text mode translates newlines.
Count-checked block I/O
fread(buf, sizeof *buf, n, fp) returns items actually read — short counts mean EOF or error, never ignore them.
Seek and tell
fseek(fp, 0, SEEK_END) + ftell(fp) measures file size; fseek(fp, pos, SEEK_SET) jumps to records by index.
Layout caveats apply
Padding, endianness, and type sizes travel with binary dumps — same-machine checkpoints, not exchange formats.
#include <stdio.h> int main(void) { int vals[3] = {10, 20, 30}; FILE *f = fopen("nums.bin", "wb"); if (!f) return 1; fwrite(vals, sizeof *vals, 3, f); fclose(f); int back[3] = {0}; f = fopen("nums.bin", "rb"); size_t got = f ? fread(back, sizeof *back, 3, f) : 0; if (f) fclose(f); printf("%d %d (got %zu)\n", back[0], back[2], got); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.