Reading history

C Binary Files: fseek, ftell and Random Access

7 min read 2 views

Read, write and update fixed-size records in C binary files with fread, fwrite, fseek, ftell and r+b mode, using random access.

A text file is read from top to bottom. A binary file of fixed-size records works more like an array on disk: you can jump straight to record 5000, read it, change it and write it back, without touching the other records. This is called random access, and it is how simple databases, game save files and many file formats work. In C you do it with fseek, ftell, fread and fwrite.

In this lesson you will learn

  • Writing and reading whole structs with fwrite and fread
  • Moving around a file with fseek and SEEK_SET, SEEK_CUR, SEEK_END
  • Finding the position and the file size with ftell
  • Updating one record in place with "r+b" mode
  • Appending, and detecting the end of the file

You should know structures, reading and writing structures in files and file error handling.

Jumping Around a File

#include <stdio.h>
#include <string.h>

struct Student {
    int roll;
    char name[20];
    float cgpa;
};

int main(void) {
    struct Student list[] = {
        {101, "Nusrat", 3.82f}, {102, "Arif", 3.41f},
        {103, "Tania", 3.95f},  {104, "Rafi", 2.98f},
    };
    const char *path = "students.dat";

    /* Write all records in binary: one fwrite call */
    FILE *f = fopen(path, "wb");
    if (!f) { perror("fopen"); return 1; }
    size_t written = fwrite(list, sizeof list[0], 4, f);
    fclose(f);
    printf("wrote %zu records of %zu bytes each\n", written, sizeof list[0]);

    f = fopen(path, "rb");
    if (!f) { perror("fopen"); return 1; }

    /* ftell after fseek to the end gives the file size */
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    printf("file size: %ld bytes = %ld records\n", size, size / (long)sizeof(struct Student));

    /* Jump straight to record 2 (the third one) without reading the others */
    struct Student s;
    fseek(f, 2 * (long)sizeof s, SEEK_SET);
    if (fread(&s, sizeof s, 1, f) != 1) return 1;
    printf("record 2: %d %s %.2f\n", s.roll, s.name, s.cgpa);
    printf("position now: %ld\n", ftell(f));

    /* Step back one record from the current position */
    fseek(f, -(long)sizeof s, SEEK_CUR);
    if (fread(&s, sizeof s, 1, f) != 1) return 1;
    printf("re-read:  %d %s\n", s.roll, s.name);

    /* rewind goes back to the start */
    rewind(f);
    if (fread(&s, sizeof s, 1, f) != 1) return 1;
    printf("first:    %d %s\n", s.roll, s.name);

    /* Reading past the end: fread returns 0 and feof becomes true */
    fseek(f, 0, SEEK_END);
    size_t got = fread(&s, sizeof s, 1, f);
    printf("read at end returned %zu, feof=%d\n", got, feof(f) != 0);

    fclose(f);
    remove(path);
    return 0;
}

Output

wrote 4 records of 28 bytes each
file size: 112 bytes = 4 records
record 2: 103 Tania 3.95
position now: 84
re-read:  103 Tania
first:    101 Nusrat
read at end returned 0, feof=1
  • The "b" in "wb" and "rb" means binary mode. On Windows it stops C from changing line-ending bytes; on Linux it makes no difference, but always write it for binary data.
  • fwrite(list, sizeof list[0], 4, f) writes 4 records of 28 bytes each in one call and returns how many were written.
  • Because every record has the same size, record k starts at byte k × 28. fseek(f, 2 * sizeof s, SEEK_SET) jumps straight to the third record.
  • SEEK_SET counts from the start, SEEK_CUR from the current position, and SEEK_END from the end. A negative offset with SEEK_CUR moves backwards, so the program re-read the same record.
  • ftell returns the current position in bytes. After seeking to the end, it gives the file size: 112 bytes, or 4 records.
  • rewind(f) goes back to the start. Reading at the end returns 0, and then feof becomes true.
  • Every fread result is checked, so a short or damaged file cannot leave the program using half-filled data.

Updating a Record in Place

#include <stdio.h>
#include <string.h>

struct Account { int id; char owner[16]; long balance; };

/* Update one record in place: open with "r+b", seek, overwrite */
static int update_balance(const char *path, int index, long new_balance) {
    FILE *f = fopen(path, "r+b");
    if (!f) return -1;
    struct Account a;
    long offset = index * (long)sizeof a;
    if (fseek(f, offset, SEEK_SET) != 0 || fread(&a, sizeof a, 1, f) != 1) {
        fclose(f);
        return -1;
    }
    a.balance = new_balance;
    fseek(f, offset, SEEK_SET);           /* must seek between a read and a write */
    fwrite(&a, sizeof a, 1, f);
    fclose(f);
    return 0;
}

static void print_all(const char *path) {
    FILE *f = fopen(path, "rb");
    if (!f) return;
    struct Account a;
    while (fread(&a, sizeof a, 1, f) == 1)
        printf("  %d %-8s %7ld\n", a.id, a.owner, a.balance);
    fclose(f);
}

int main(void) {
    const char *path = "accounts.dat";
    struct Account start[] = {{1, "Karim", 5000}, {2, "Mitu", 12000}, {3, "Sabbir", 800}};
    FILE *f = fopen(path, "wb");
    if (!f) return 1;
    fwrite(start, sizeof start[0], 3, f);
    fclose(f);

    printf("before:\n");
    print_all(path);
    update_balance(path, 1, 15500);
    printf("after updating record 1:\n");
    print_all(path);

    /* Append mode always writes at the end */
    f = fopen(path, "ab");
    struct Account extra = {4, "Tania", 2300};
    fwrite(&extra, sizeof extra, 1, f);
    fclose(f);
    printf("after appending:\n");
    print_all(path);

    printf("update record 9: %s\n", update_balance(path, 9, 1) == 0 ? "ok" : "failed (no such record)");
    remove(path);
    return 0;
}

Output

before:
  1 Karim       5000
  2 Mitu       12000
  3 Sabbir       800
after updating record 1:
  1 Karim       5000
  2 Mitu       15500
  3 Sabbir       800
after appending:
  1 Karim       5000
  2 Mitu       15500
  3 Sabbir       800
  4 Tania       2300
update record 9: failed (no such record)
  • "r+b" opens an existing file for both reading and writing, without erasing it. ("w+b" would empty it first.)
  • update_balance seeks to the record, reads it, changes one field, seeks back to the same place and writes it. Only those 32 bytes on disk change.
  • The C standard requires a positioning call such as fseek when you switch from reading to writing on the same stream (and fseek or fflush when you switch the other way). That is why the code seeks again before fwrite.
  • "ab" (append) always writes at the end of the file, whatever the position.
  • Asking for record 9 fails cleanly: the seek works, but fread returns 0 because there is no data there, and the function reports an error.
ModeReadWriteFile must existErases file
"rb"YesNoYesNo
"wb"NoYesNoYes
"ab"NoYes, at endNoNo
"r+b"YesYesYesNo
"w+b"YesYesNoYes

A Word About Portability

Writing structs straight to disk is quick and simple, but the file is tied to the computer that wrote it. A different compiler or CPU may use different padding, different sizes for long, or a different byte order. For files that must move between systems, use fixed-width types and write each field in a fixed byte order.

Common Mistakes

  1. Opening with "w+b" to update a file, which erases it. Use "r+b".
  2. Switching between reading and writing without a seek. The result is undefined.
  3. Not checking fread‘s return value, and then using a struct that was never filled.
  4. Writing structs that contain pointers. The file stores the address, not the text it points to. Use fixed-size char arrays instead.

Practice Exercises

Exercise 1. Write a function long count_records(FILE *f, size_t rec_size) that returns how many records a binary file holds, without reading them.

Show answer
long count_records(FILE *f, size_t rec_size) {
    long here = ftell(f);              /* remember the position */
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    fseek(f, here, SEEK_SET);          /* put it back */
    return size / (long)rec_size;
}

Exercise 2. In the student file from the first program, at which byte does record 3 (the fourth record) start?

Show answer

3 × 28 = 84. Record numbers start at 0, and each record is 28 bytes.

Frequently Asked Questions

What if a file is bigger than 2 GB?

ftell returns a long, which is only 32 bits on some systems. For very large files use fseeko/ftello on Linux and macOS, or _fseeki64/_ftelli64 on Windows.

How do I delete a record from the middle of the file?

Files cannot shrink from the middle. Common choices are to mark the record as deleted with a flag field, or to copy all the other records into a new file and replace the old one.

Summary

  • Fixed-size records let you jump to any record with fseek(f, k * size, SEEK_SET).
  • ftell gives the position; at the end it gives the file size.
  • "r+b" updates records in place; seek between reads and writes.
  • Check every fread, and avoid pointers inside saved structs.

Next: Endianness and Byte Order in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *