devnotes.

File Positioning and Binary Files

Beyond sequential reading, C lets you jump around within a file and work with raw binary data instead of text.

#include <stdio.h>

typedef struct { int id; float score; } Record;

int main(void) {
    Record r1 = {1, 95.5f};
    FILE *f = fopen("data.bin", "wb");   // "b" = binary mode
    fwrite(&r1, sizeof(Record), 1, f);   // write raw bytes of the struct
    fclose(f);

    Record r2;
    f = fopen("data.bin", "rb");
    fread(&r2, sizeof(Record), 1, f);    // read them back
    printf("%d %f\n", r2.id, r2.score);

    fseek(f, 0, SEEK_END);   // move to the end
    long size = ftell(f);    // report current position -> file size in bytes
    rewind(f);               // jump back to the beginning (same as fseek(f, 0, SEEK_SET))
    fclose(f);
    return 0;
}

fread/fwrite transfer raw bytes directly, which is far faster than formatting/parsing text with fprintf/fscanf for structured data — but the resulting file isn't human-readable, and its exact byte layout can differ across compilers, platforms, or CPU architectures (padding, alignment, and endianness), so binary files written by one system aren't always portable to another without care.

fseek(file, offset, origin) moves the internal read/write position; origin is one of SEEK_SET (from the start), SEEK_CUR (from the current position), or SEEK_END (from the end, usually with a negative offset). ftell reports the current position as a byte offset — the size-via-ftell trick above is a common idiom for getting a file's total size. Opening a file with "b" in the mode string ("rb", "wb") is required on some platforms (notably Windows) to disable automatic text-mode line-ending conversion, which would otherwise silently corrupt binary data.

File Positioning and Binary Files in C | DevNotes