Learn C
#include "ioformatting/binary_positioning.h"

Binary I/O & File Positioning in C

#concept

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.

#how it works
1

Binary modes

"rb"/"wb" pass bytes through untouched — mandatory on Windows where text mode translates newlines.

2

Count-checked block I/O

fread(buf, sizeof *buf, n, fp) returns items actually read — short counts mean EOF or error, never ignore them.

3

Seek and tell

fseek(fp, 0, SEEK_END) + ftell(fp) measures file size; fseek(fp, pos, SEEK_SET) jumps to records by index.

4

Layout caveats apply

Padding, endianness, and type sizes travel with binary dumps — same-machine checkpoints, not exchange formats.

#example
#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;
}
Output
10 30 (got 3)
1fwrite dumps three ints verbatim — 12 exact bytes, no formatting.
2fread pulls three items back; got == 3 confirms the full read.
3First and last values plus the count print — round trip verified numerically.
#use cases
Checkpoint and save files with verbatim struct dumps
Indexed record access via fseek arithmetic
File sizing with seek-end plus ftell
Count-checked reads that never trust partial data

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.