04. Random Access File Seeking (fseek, ftell, rewind)

🟡 Difficulty: Intermediate | File Stream Cursor Positioning, File Size Measurement & Direct Record Access

📖 Definition

Random access file seeking in C allows moving the file stream read/write position cursor directly to any byte location inside a file without scanning sequentially from the beginning. fseek() sets the cursor offset, ftell() returns the current byte position, and rewind() resets the cursor back to byte offset 0.

🎯 Why It Is Used

  • O(1) Direct Record Retrieval: Reading record #N in a fixed-size binary database file directly: fseek(fp, N * sizeof(Record), SEEK_SET);.
  • Measuring Total File Size: Seeking to SEEK_END and calling ftell() returns the exact file byte size.
  • In-Place Binary File Updates: Modifying specific binary header bytes or record fields without re-writing the entire file.

⚙️ How It Works: Seeking Origin Flags

When calling fseek(fp, offset, origin), the byte position is calculated relative to one of three origin constants:

Origin Constant Reference Point Offset Example
SEEK_SET Beginning of File (Byte 0) fseek(fp, 100, SEEK_SET) (Jump to byte offset 100)
SEEK_CUR Current Cursor Position fseek(fp, 20, SEEK_CUR) (Advance forward 20 bytes)
SEEK_END End-Of-File (EOF) fseek(fp, -10, SEEK_END) (Move 10 bytes back from end)

📝 Syntax

#include <stdio.h>

// 1. Move file cursor
int err = fseek(FILE *stream, long offset, int origin); // Returns 0 on success

// 2. Query current cursor byte offset
long pos = ftell(FILE *stream); // Returns current byte position or -1L on error

// 3. Reset cursor to file beginning
rewind(FILE *stream); // Equivalent to fseek(stream, 0L, SEEK_SET)

🔀 Measuring File Size Idiom

fseek(fp, 0L, SEEK_END);
long file_size_bytes = ftell(fp);
rewind(fp); // Reset cursor back to start for subsequent reads!

🌱 Beginner Example: File Size Measurement

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("sample.txt", "w+"); // Create and open for read/write
    if (fp == NULL) return 1;

    fputs("1234567890", fp); // Write 10 bytes

    // Seek to end and get byte offset
    fseek(fp, 0L, SEEK_END);
    long size = ftell(fp);

    printf("File sample.txt Size: %ld bytes\n", size);

    fclose(fp);
    return 0;
}

🌼 Intermediate Example: Direct O(1) Record Access in Binary File

#include <stdio.h>

typedef struct {
    int id;
    char code[8];
} Record;

int main(void) {
    // Write 3 records to database
    Record db[3] = {{10, "A1"}, {20, "B2"}, {30, "C3"}};
    FILE *fp = fopen("db.dat", "w+b");
    if (fp == NULL) return 1;

    fwrite(db, sizeof(Record), 3, fp);

    // Jump directly to Record #2 (Index 1) in O(1) time
    int target_index = 1;
    fseek(fp, target_index * sizeof(Record), SEEK_SET);

    Record target_rec;
    if (fread(&target_rec, sizeof(Record), 1, fp) == 1) {
        printf("=== Random Access Record #%d ===\n", target_index);
        printf("ID  : %d\n", target_rec.id);
        printf("Code: %s\n", target_rec.code);
    }

    fclose(fp);
    return 0;
}

🌲 Advanced Example: In-Place Binary File Mutation

#include <stdio.h>

typedef struct {
    int id;
    int score;
} Account;

int main(void) {
    // Initialize file with 3 accounts
    Account accounts[3] = {{101, 50}, {102, 60}, {103, 70}};
    FILE *fp = fopen("game_data.bin", "w+b");
    if (fp == NULL) return 1;

    fwrite(accounts, sizeof(Account), 3, fp);

    // Update Account #1 (Index 1) score to 99 in-place
    fseek(fp, 1 * sizeof(Account), SEEK_SET);
    Account update = {102, 99};
    fwrite(&update, sizeof(Account), 1, fp);

    // Read back all accounts to verify in-place edit
    rewind(fp);
    Account temp;
    printf("=== Updated Game Accounts ===\n");
    while (fread(&temp, sizeof(Account), 1, fp) == 1) {
        printf("Account ID: %d | Score: %d\n", temp.id, temp.score);
    }

    fclose(fp);
    return 0;
}

🔍 Line-by-Line Explanation

  • fseek(fp, target_index * sizeof(Record), SEEK_SET);: Calculates exact byte offset for Record #1 and moves file pointer cursor directly to that byte location in RAM/disk stream.
  • long size = ftell(fp);: Reads the current byte offset relative to file start, returning total file size when positioned at SEEK_END.
  • rewind(fp);: Resets file stream cursor back to offset 0 and clears stream error flags.

💻 Expected Terminal Output

File sample.txt Size: 10 bytes
=== Random Access Record #1 ===
ID  : 20
Code: B2
=== Updated Game Accounts ===
Account ID: 101 | Score: 50
Account ID: 102 | Score: 99
Account ID: 103 | Score: 70

⚠️ Common Mistakes & Pitfalls

  • Forgetting rewind() or fseek() After SEEK_END: Seeking to SEEK_END to measure size leaves the cursor at EOF. Attempting to call fread() immediately after without rewinding fails!
  • Using Text Mode Seeking on Windows: Seeking arbitrary byte offsets in text mode ("r" / "w") on Windows causes inaccurate offset calculations due to \r\n translation. Always use binary modes ("rb" / "wb" / "r+b") for byte-exact seeking.

📌 Important Rules & Limitations

  • fseek() returns 0 on success and non-zero on failure.
  • For binary random access, always open streams using binary access modes.
  • Always reset or reposition file cursor after reaching EOF before calling subsequent read routines.

🌐 Multilingual Explanation: English

Random access file seeking uses fseek(), ftell(), and rewind() to jump directly to any byte location. It enables $O(1)$ binary record access and file size measurement.

🌐 Multilingual Explanation: Hindi (Roman Script)

Random access seeking ke zariye hum fseek() se file cursor ko kisi bhi byte par jump kara sakte hain. Single record badalne ya file size napne ke liye ye sabse fast tariqa hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

File cursor la direct konthyahi byte var jau dhenyasathi fseek() vapartat. File size milvanyasathi ftell() aani reset sathi rewind() vapra.

❓ Practice Questions

  1. What are the three origin constants used by fseek()?
  2. How do you calculate the exact byte size of a file using fseek() and ftell()?
  3. Why must you call rewind() or fseek(fp, 0, SEEK_SET) after seeking to SEEK_END to measure file size?

🚀 Practical Coding Challenge

Write a C program named binary_record_updater.c that opens a binary file containing 10 integer values, uses fseek() to jump directly to the 5th integer (index 4), updates its value to 999 in-place, and reads the entire file back.

🧭 Navigation & Breadcrumbs

← Previous: 03. Binary File I/O | Module 16 Guide | Next Module: 17. Preprocessor & Macros →