C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. File Handling in C
  5. Random access in File

Random access in File

Learn about Random Access in File Handling in C programming using fseek(), ftell(), and rewind(). Understand how to read and write data at specific locations in files.


Introduction

In C programming, random access in files allows a programmer to directly jump to any part of a file and perform read or write operations — without processing it from the beginning.

Unlike sequential file access, where data is read or written in order, random access lets you move the file pointer to a specific byte position and access data instantly.

This technique is essential for handling large files, database systems, or binary files, where quick and flexible access to data is required.


What is Random File Access?

Random access means the program can directly go to any position within a file and perform operations like read, write, or modify.

C provides several functions for random file access:

  • fseek() – Moves file pointer to a specified location.
  • ftell() – Returns current position of file pointer.
  • rewind() – Resets file pointer to the beginning of file.

These functions are defined in the stdio.h library.


1. fseek() – Moving File Pointer

The fseek() function sets the position of the file pointer to a specific byte offset in a file.

Syntax:

fseek(FILE *stream, long int offset, int position);

Parameters:

  • stream → file pointer
  • offset → number of bytes to move
  • position → starting point for offset (SEEK_SET, SEEK_CUR, SEEK_END)
ConstantDescription
SEEK_SETBeginning of file
SEEK_CURCurrent file pointer position
SEEK_ENDEnd of file

Example:

#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "r");

    if (fp == NULL) {
        printf("File not found!\n");
        return 1;
    }

    fseek(fp, 10, SEEK_SET); // Move 10 bytes from beginning
    char ch = fgetc(fp);
    printf("Character at position 10: %c\n", ch);

    fclose(fp);
    return 0;
}

Explanation:
The file pointer moves 10 bytes from the start, and the program reads the character at that position.


2. ftell() – Getting Current File Pointer Position

The ftell() function returns the current position of the file pointer in bytes from the beginning of the file.

Syntax:

long int ftell(FILE *stream);

Example:

#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "r");
    fseek(fp, 0, SEEK_END); // Move pointer to end
    long int pos = ftell(fp);

    printf("File size: %ld bytes\n", pos);
    fclose(fp);
    return 0;
}

Explanation:
By moving to the end and using ftell(), you can determine the total size of the file.


3. rewind() – Resetting File Pointer

The rewind() function moves the file pointer back to the beginning of the file.

Syntax:

rewind(FILE *stream);

Example:

rewind(fp);

Use Case:
After reading or writing at random positions, rewind() is used to reset the file pointer for reprocessing from the start.


Example: Random Access File Operations

#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("students.dat", "w+");

    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    fprintf(fp, "Alice\nBob\nCharlie\nDavid\nEve\n");

    fseek(fp, 10, SEEK_SET);  // Move 10 bytes from start
    fprintf(fp, "Zara\n");    // Overwrite data at position 10

    rewind(fp);
    printf("Updated File Content:\n");

    char ch;
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);

    fclose(fp);
    return 0;
}

Output:

Alice
Bob
Zara
avid
Eve

Explanation:
The program writes names, moves the pointer using fseek(), overwrites at a specific location, and then reads the updated content.


Practical Applications of Random File Access

  • Updating specific records in a large database file
  • Reading data from a specific byte offset
  • Editing binary files efficiently
  • Implementing index-based storage systems
  • Handling structured data (like employee or student records)

Sequential vs Random File Access

FeatureSequential AccessRandom Access
Data AccessLinearly, from start to endAny position directly
SpeedSlower for large filesFaster for large files
ControlLimitedFull control
Use CaseLogs, streamingDatabases, binary files

Important Points to Remember

✅ Always check if file pointer is NULL before using it.
✅ Use fseek() carefully to avoid reading past file end.
✅ Combine ftell() and fseek() to calculate positions dynamically.
✅ Always close the file using fclose() after operations.


Conclusion

Random access in file handling in C provides the ability to manipulate data at any position without reading the entire file.

By mastering fseek(), ftell(), and rewind(), you can efficiently build high-performance programs that handle large files, manage databases, or process binary data.

It’s a core concept for system programmers, embedded developers, and data engineers working with C.

Tags , ,

How can we help?

Leave a Reply

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