Random File Access with fseek, ftell, rewind — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Demonstrate Random File Access Using fseek(), ftell(), and rewind()

In this tutorial, you'll learn how to perform random file access using C's file-positioning functions: fseek(), ftell(), and rewind(). Up to now, every file program in this series has read or written the file sequentially, one byte after another. Random access lets you jump to any position in the file — a specific record in a database, the header of an image, the trailer of a log — without reading everything before it. This is what makes databases, file formats like PNG and MP4, and any indexed file structure possible.

C program to demonstrate random file access using fseek, ftell, and rewind on a binary file, with step-by-step explanation.

📝 Problem Statement

Write a program in C to demonstrate random file access using fseek(), ftell(), and rewind().

⚙️ How the Program Works

The program opens a binary file, reads some bytes, jumps to specific positions, reports its position at each step, and demonstrates the three functions in a single walk-through:

  1. Open the file in binary read mode ("rb").
  2. Read the first 5 bytes with fread(). Now the position is at byte 5.
  3. Report the position with ftell(fp) — it returns 5.
  4. Jump to byte offset 10 with fseek(fp, 10, SEEK_SET). The next read starts at byte 10.
  5. Read 1 byte and print it. The position is now at byte 11.
  6. Jump to the end of the file with fseek(fp, 0, SEEK_END), then call ftell(fp) to get the file size.
  7. Jump backwards by 5 bytes from the current position with fseek(fp, -5, SEEK_CUR).
  8. Reset to the beginning with rewind(fp) — equivalent to fseek(fp, 0, SEEK_SET).
  9. Read the first byte again to confirm we're back at the start.

🧠 Understanding the Three Functions

All three functions operate on the file position indicator — a "cursor" that tells the next read or write where to start. The three functions manipulate that cursor:

  • ftell(fp) — reports the current byte offset from the beginning of the file. Returns long, or -1 on error.
  • fseek(fp, offset, whence) — moves the cursor. offset is a signed byte count; whence is where the offset is measured from (see the table below).
  • rewind(fp) — moves the cursor to byte 0 and clears the error indicator. Shorthand for fseek(fp, 0, SEEK_SET); clearerr(fp);.

The whence parameter

Constant Meaning Example
SEEK_SET Offset is from the start of the file fseek(fp, 100, SEEK_SET) → go to byte 100
SEEK_CUR Offset is from the current position fseek(fp, -5, SEEK_CUR) → go back 5 bytes
SEEK_END Offset is from the end of the file fseek(fp, -10, SEEK_END) → go to 10 bytes before the end

💻 Complete C Program

#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; char buf[8]; long size, pos; int ch; /* Create a sample file of 26 bytes to work with */ fp = fopen("demo.bin", "wb"); if (fp == NULL) { printf("Error creating file.\n"); return 1; } for (int i = 0; i < 26; i++) fputc('A' + i, fp); /* A B C ... Z */ fclose(fp); /* Now reopen for reading and demonstrate the three functions */ fp = fopen("demo.bin", "rb"); if (fp == NULL) { printf("Error opening file.\n"); return 1; } /* 1. Read the first 5 bytes */ fread(buf, 1, 5, fp); buf[5] = '\0'; printf("Read first 5 bytes: %s\n", buf); printf("ftell() = %ld\n\n", ftell(fp)); /* 2. Jump to byte 10 using SEEK_SET */ fseek(fp, 10, SEEK_SET); printf("After fseek(10, SEEK_SET): ftell() = %ld\n", ftell(fp)); ch = fgetc(fp); printf("Read byte at offset 10: '%c'\n", ch); printf("ftell() = %ld\n\n", ftell(fp)); /* 3. Find file size using SEEK_END */ fseek(fp, 0, SEEK_END); size = ftell(fp); printf("File size (fseek to SEEK_END + ftell): %ld bytes\n\n", size); /* 4. Move backwards 5 bytes from current position using SEEK_CUR */ fseek(fp, -5, SEEK_CUR); pos = ftell(fp); printf("After fseek(-5, SEEK_CUR): ftell() = %ld\n", pos); ch = fgetc(fp); printf("Read byte at offset %ld: '%c'\n\n", pos, ch); /* 5. rewind() — reset to the beginning */ rewind(fp); printf("After rewind(): ftell() = %ld\n", ftell(fp)); ch = fgetc(fp); printf("Read byte after rewind: '%c'\n", ch); fclose(fp); return 0; }

🖥️ Sample Output

Console: Read first 5 bytes: ABCDE
ftell() = 5

After fseek(10, SEEK_SET): ftell() = 10
Read byte at offset 10: 'K'
ftell() = 11

File size (fseek to SEEK_END + ftell): 26 bytes

After fseek(-5, SEEK_CUR): ftell() = 21
Read byte at offset 21: 'V'

After rewind(): ftell() = 0
Read byte after rewind: 'A'

🔍 Line-by-Line Explanation

Line / Code Explanation
fputc('A' + i, fp) Writes the bytes 'A', 'B', 'C', ..., 'Z' — a 26-byte file for demonstration.
fread(buf, 1, 5, fp) Reads 5 bytes into buf. After this call, the cursor is at byte 5 (just past the last byte read).
ftell(fp) Returns the current byte offset from the start. After reading 5 bytes, it returns 5.
fseek(fp, 10, SEEK_SET) Moves the cursor to byte 10. The next fgetc reads byte 10 (the 11th byte).
fgetc(fp) Reads one byte and advances the cursor by 1. That's why ftell reports 11 after this.
fseek(fp, 0, SEEK_END) Moves the cursor to the end of the file. Combined with ftell, this is the standard way to get a file's size.
fseek(fp, -5, SEEK_CUR) Moves the cursor back 5 bytes from wherever it is now. After being at position 26 (end), it lands at 21.
rewind(fp) Moves the cursor to byte 0 and clears the error indicator. Equivalent to fseek(fp, 0, SEEK_SET) plus clearerr(fp).
fclose(fp) Closes the file. The demo file demo.bin remains on disk.
⚠️ Important: fseek only guarantees correct positioning on files opened in binary mode. On text-mode files (especially on Windows), the byte offset that fseek accepts may not match what you expect, and the standard only guarantees that fseek(fp, 0, SEEK_SET) and fseek(fp, ftell_position, SEEK_SET) work. For precise random access, always use "rb"/"wb".

🎯 Common Use Cases

These three functions power almost every random-access file pattern in C:

Task Code
Find a file's size fseek(fp, 0, SEEK_END); size = ftell(fp);
Read record N of a struct-array file fseek(fp, N * sizeof(struct S), SEEK_SET); fread(&s, sizeof(struct S), 1, fp);
Rewrite a record in place fseek(fp, N * sizeof(struct S), SEEK_SET); fwrite(&s, sizeof(struct S), 1, fp); (needs "rb+")
Read the last 8 bytes of a file fseek(fp, -8, SEEK_END); fread(buf, 1, 8, fp);
Skip a fixed-size header fseek(fp, HEADER_SIZE, SEEK_SET);
Iterate a file twice rewind(fp) between passes
Append a record at the end fseek(fp, 0, SEEK_END); fwrite(&s, sizeof(s), 1, fp); (or open in "ab")

🐛 Common Pitfalls

  • Text-mode files: On Windows, byte offsets in text mode don't match the actual file bytes because of \r\n translation. Always use "rb"/"rb+" for random access.
  • Forgetting that reads advance the cursor: ftell after fread reflects the position after the read, not before.
  • Reading past end-of-file: fseek can position past EOF, but the next read returns EOF. Check for that when computing sizes or reading tails.
  • Negative offsets without SEEK_END: fseek(fp, -5, SEEK_SET) is undefined behavior — the offset would be negative. Use SEEK_END or SEEK_CUR for negative offsets.
  • Not handling fseek errors: fseek returns 0 on success, non-zero on failure. Ignoring the return value can mask bugs (e.g., seeking past the end of a pipe, which is unseekable).
  • Seeking on a pipe or terminal: Pipes and stdin are not seekable — fseek fails on them. Random access requires a regular file.
  • Using fseek on files opened with "a": Writes always go to the end regardless of position. Use "rb+" or "wb+" for read-and-write with positioning.

💡 Tips & Best Practices

  • Store the file size in a long (or long long for files larger than 2 GB on 32-bit systems) — ftell returns long.
  • Between a write and a read on the same file, call fflush(fp) first — the C standard requires it for streams opened with "+".
  • For files larger than 2 GB on POSIX systems, use fseeko/ftello with off_t instead of fseek/ftell.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch format-specifier mismatches with long.
  • Use xxd demo.bin on Linux to see the raw bytes and confirm your offsets are correct.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 16. Store and Retrieve Student Records Using Structures and Binary Files
  • 7. Write Data to a Binary File
  • 8. Read Binary Data from a Binary File and Display It
  • 3. Append Data to an Existing Binary File
  • Binary Files in C — Overview
  • Files FAQ

Previous Problem: -->> 16. Store and Retrieve Student Records Using Structures and Binary Files   ||   Next Problem: -->> 18. Build a Simple Bank Account Management System

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.