View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

A Comprehensive Guide to Random Access Files in C

Updated on 05/05/20253,582 Views

In the world of file handling, random access files in C give programmers the power to jump straight to any part of a file—no need to start from the beginning each time. Unlike sequential file access, where data is read or written in a linear order, random access files in C allow direct access to any record, making them perfect for applications like databases, file indexing systems, or when speed and precision matter.

If you’ve ever worked with large data sets or needed to update only a portion of a file without affecting the rest, you’ve brushed up against the power of random access files in C. This technique is widely used in systems programming and is often a go-to strategy when working with fixed-length records or when minimizing disk read/write times is crucial. Because of all such reasons, this concept is also included in all top-tier software development courses

In this blog, we’ll demystify the concept of random access files in C, walk through how they work, and look at real-world examples. We’ll also dive into the key functions like fseek(), ftell(), and rewind(), which are central to manipulating file pointers.

Types of Random Access Files in C

When working with random access files in C, it’s important to understand that the type of file structure you choose directly affects how you’ll read, write, and navigate through the file. Typically, there are two primary types of random access files in C, and each serves different use cases based on how data is stored and retrieved.

Also, before you move further, you should also learn about the basic structure of C program to solidify your fundamentals. 

1. Binary Random Access Files

Binary files store data in raw binary format, which is exactly how it's represented in memory. This method is faster and more space-efficient, making it ideal for storing structured data like records, arrays, or structs.

Advantages:

  • No conversion required between text and binary
  • Smaller file size
  • Faster read/write performance

2. Text Random Access Files

Text files, on the other hand, store data in readable text format. While they’re human-readable and easier to debug, working with random access files in C in text mode can be tricky because line lengths can vary, and finding the exact position of a specific record can be difficult.

Advantages:

  • Human-readable
  • Easy to inspect with standard text editors

Why the Distinction Matters

Understanding the distinction between these two types is vital when building random access files in C, as file handling functions like `fread()` and `fwrite()` behave differently depending on the file mode (text or binary). Binary mode is typically preferred for true random access because every byte has a predictable position, which makes pointer arithmetic much more reliable.

Build a future-forward career with the following in-demand online courses: 

Functions of Random Access Files in C

To truly harness the power of random access files in C, you need to be familiar with the core set of file handling functions that make random access possible. These functions work together to help you manipulate the file pointer, read or write data at specific positions, and retrieve information about file structure.

To strengthen your understanding about the functions, you should explore our articles: 

Now, let’s go over the essential functions used in random access files in C:

1. `fopen()`

Purpose: Opens a file in a specific mode (e.g., read, write, binary).

Use in random access: Opens the file in binary mode (`"rb"`, `"wb"`, `"rb+"`, etc.) for non-sequential access.

2. `fseek()`

Purpose: Moves the file pointer to a specified location.

Use in random access: Crucial for jumping to a specific byte position in the file.

3. `ftell()`

Purpose: Returns the current position of the file pointer.

Use in random access: Helps track your position or know where to return after performing other operations.

4. `rewind()`

Purpose: Moves the file pointer back to the beginning of the file.

Use in random access: Handy when you want to restart operations from the start without closing and reopening the file.

5. `fread()` and `fwrite()`

Purpose: Read from or write to a file in binary mode.

Use in random access: These are your primary tools for reading or updating specific data blocks.

6. `fclose()`

Purpose: Closes an open file.

Use in random access: Ensures all buffers are flushed and resources are released.

Why These Functions Matter

Each of these functions contributes to making random access files in C efficient and practical. Whether you're developing a database engine or managing a file-based index, these tools allow you to surgically access and modify only the parts of the file you need—without wasting time on the rest.

Creating a Random Access File in C

Before you can perform random read/write operations, you need to create a file that supports non-sequential access. In C, this is typically done using binary mode so that every record occupies a fixed and predictable number of bytes. This consistency is essential for accurately seeking to specific locations in the file.

Before you begin with the code examples, go through our following articles to gain insights about C programs: 

In the following example, we’ll create a binary file called `data.dat` and write a few structured records into it. This file will be the basis for our later operations involving random access files in C.

#include <stdio.h>
#include <stdlib.h>

// Define a structure to represent a record
typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;

    // Open the file in write-binary mode
    fp = fopen("data.dat", "wb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Write three records into the file
    for (int i = 0; i < 3; i++) {
        r.id = i + 1;
        snprintf(r.name, sizeof(r.name), "Record %d", r.id);
        fwrite(&r, sizeof(Record), 1, fp);  // Write struct to file
    }

    fclose(fp);  // Close the file
    printf("File created and records written successfully.\n");
    return 0;
}

Explanation

  • We define a `Record` structure to simulate real-world data storage.
  • The file is opened in `"wb"` mode, which means *write in binary*.
  • Using `fwrite()`, each record is written to the file in binary form.
  • Because each record is of fixed size, we can easily calculate where any given record begins, which is key to random access.

Output

File created and records written successfully.

This sets the stage for performing advanced operations like editing a specific record, jumping to any byte in the file, and efficiently managing large datasets using random access files in C.

Writing Data Randomly to a Random Access File in C

One of the main advantages of using random access files in C is the ability to jump directly to a specific part of the file and modify just that section. This is particularly useful when working with fixed-size records, as you can calculate the exact byte offset of any record and update it without affecting others.

In this example, we’ll modify the second record in the binary file `data.dat` that we created earlier. This demonstrates how to use `fseek()` to navigate to a specific location and `fwrite()` to overwrite data at that position.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;

    // Open file in read/write binary mode
    fp = fopen("data.dat", "rb+");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Create a new record to overwrite the second record
    r.id = 2;
    snprintf(r.name, sizeof(r.name), "Updated Record 2");

    // Move file pointer to the second record
    fseek(fp, sizeof(Record) * 1, SEEK_SET); // Index 1 = second record

    // Write the new data over the existing second record
    fwrite(&r, sizeof(Record), 1, fp);

    fclose(fp); // Close the file
    printf("Second record updated successfully.\n");
    return 0;
}

Explanation

  • The file is opened in `"rb+"` mode, which allows reading and writing without truncating the file.
  • `fseek()` moves the file pointer to the second record by skipping the size of one `Record` (indexing starts at 0).
  • `fwrite()` then overwrites the record at that position.
  • This is a classic use case of random access files in C, where we target a specific part of the file without disturbing the rest.

Output

Second record updated successfully.

This technique is highly efficient when dealing with large files where reading or rewriting the entire file would be too costly. It shows the real power of random access files in C: precision and performance.

How to Use the ftell() Function in C?

The `ftell()` function is a key part of working with random access files in C. It helps you determine the current position of the file pointer, which is especially useful when you're navigating large files or need to keep track of where you are during read/write operations.

Syntax

long ftell(FILE *stream);

  • Returns: The current file position as a long integer.
  • Returns -1L on error.

In the following example, we'll read a record from a file and use `ftell()` to find out where in the file we currently are. This gives us insight into how random access files in C manage internal byte offsets.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;

    // Open the file in read-binary mode
    fp = fopen("data.dat", "rb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Read the first record
    fread(&r, sizeof(Record), 1, fp);

    // Get the current position of the file pointer
    long position = ftell(fp);

    // Display the data and the current position
    printf("Read Record: ID = %d, Name = %s\n", r.id, r.name);
    printf("File pointer is at byte position: %ld\n", position);

    fclose(fp);
    return 0;
}

Explanation

  • We open `data.dat` in binary read mode.
  • After reading the first record using `fread()`, we call `ftell()` to find out where the file pointer is.
  • Since each record is of a fixed size, the result from `ftell()` will tell us how far we've moved into the file.

Output

Read Record: ID = 1, Name = Record 1
File pointer is at byte position: 34

Note: The exact byte offset may vary depending on padding or compiler settings, but the concept remains the same.

Also, read our article on if-else statements in C to effectively develop your C program. 

Why Use ftell()?

When dealing with random access files in C, `ftell()` is incredibly useful for:

  • Tracking progress through a file
  • Bookmarking positions for later access
  • Debugging pointer-related logic

In combination with `fseek()`, `ftell()` gives you complete control over file navigation, which is what makes random access files in C so powerful.

How to Use the rewind() Function in C?

In file handling, particularly with random access files in C, there are many situations where you may want to return to the beginning of the file—perhaps to reread data, reprocess records, or restart a loop. This is where the `rewind()` function comes into play.

Syntax

void rewind(FILE *stream);

  • Purpose: Sets the file pointer to the beginning of the file.
  • Return Value: None (void function).

In the below example, we will read the first record, then use `rewind()` to reset the file pointer, and read the first record again to demonstrate how `rewind()` works in the context of random access files in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;

    // Open the file in read-binary mode
    fp = fopen("data.dat", "rb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Read the first record
    fread(&r, sizeof(Record), 1, fp);
    printf("First Read: ID = %d, Name = %s\n", r.id, r.name);

    // Rewind to the beginning of the file
    rewind(fp);

    // Read the first record again after rewinding
    fread(&r, sizeof(Record), 1, fp);
    printf("Second Read After rewind(): ID = %d, Name = %s\n", r.id, r.name);

    fclose(fp);
    return 0;
}

Explanation

  • The file is opened in binary read mode.
  • We read the first record and print its data.
  • We then call `rewind()` to move the file pointer back to the beginning.
  • When we read again, we get the same first record, confirming that the file pointer has indeed been reset.

Output

First Read: ID = 1, Name = Record 1

Second Read After rewind(): ID = 1, Name = Record 1

However, if you’re using Linux OS, then you should explore our article on compiling C program in Linux

Why Use rewind()?

In the context of random access files in C, `rewind()` is useful for:

  • Re-reading the file from the start without reopening it.
  • Resetting loops that operate on all records.
  • Ensuring you begin operations at the file's beginning after random access jumps.

It’s a simple yet effective tool that complements functions like `fseek()` and `ftell()` for complete control over file navigation.

How to Use the fseek() Function in C?

The `fseek()` function is the cornerstone of working with random access files in C. It allows you to move the file pointer to a specific position within the file—either forward, backward, or to an absolute offset. This direct access is what makes random file operations fast and flexible.

Syntax

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

  • `stream` – The file pointer.
  • `offset` – Number of bytes to move.
  • `origin` – Starting point for offset (`SEEK_SET`, `SEEK_CUR`, or `SEEK_END`).

Constants for `origin`

  • `SEEK_SET` – Start of the file
  • `SEEK_CUR` – Current position
  • `SEEK_END` – End of the file

In the below example, we’ll use `fseek()` to jump directly to the third record in a file and read it. This is a perfect demonstration of how random access files in C let you access data at specific locations without scanning the whole file.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;

    // Open the file in read-binary mode
    fp = fopen("data.dat", "rb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Move the file pointer to the third record
    fseek(fp, sizeof(Record) * 2, SEEK_SET); // Index 2 = third record

    // Read the third record
    fread(&r, sizeof(Record), 1, fp);
    printf("Third Record: ID = %d, Name = %s\n", r.id, r.name);

    fclose(fp);
    return 0;
}

Explanation

  • The file is opened in binary read mode.
  • We calculate the offset for the third record using `sizeof(Record) * 2`.
  • `fseek()` positions the pointer exactly at the third record.
  • We then read it using `fread()` and print the result.

Output

Third Record: ID = 3, Name = Record 3

Why Use fseek()?

In random access files in C, `fseek()` is essential when:

  • You need to jump directly to a specific record or data block.
  • You want to skip over irrelevant data.
  • You’re performing targeted updates or reads.

When combined with `ftell()` and `rewind()`, `fseek()` gives you full navigation power inside your files—an absolute must for any robust C application that deals with structured file data.

How to Find a Specific Record in a Random Access File in C

A common requirement when working with random access files in C is locating and retrieving a specific record based on a known value—such as an ID or a name. Because records are often fixed in size, you can efficiently scan the file using `fread()` along with conditional logic, jumping to or reading only the necessary parts.

In the following example, we will search for a record with a specific `id` in a binary file and display it once found. This technique avoids reading the entire file into memory and is efficient for large datasets.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[30];
} Record;

int main() {
    FILE *fp;
    Record r;
    int targetId = 2;  // The ID we want to search for
    int found = 0;

    // Open the file in read-binary mode
    fp = fopen("data.dat", "rb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Read through the file record by record
    while (fread(&r, sizeof(Record), 1, fp) == 1) {
        if (r.id == targetId) {
            printf("Record found: ID = %d, Name = %s\n", r.id, r.name);
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("Record with ID = %d not found.\n", targetId);
    }

    fclose(fp);
    return 0;
}

Explanation

  • The file is opened in `"rb"` mode.
  • We loop through the file using `fread()` to read one record at a time.
  • If the `id` matches the target, we print it and exit the loop.
  • This method works efficiently with random access files in C, especially when you're looking for an arbitrary record by key.

Output (when ID = 2 exists)

Record found: ID = 2, Name = Updated Record 2

Output (when ID is not found)

Record with ID = 2 not found.

Why This Is Useful in Random Access Files in C

This search approach is helpful when:

  • You don’t know the exact byte offset of the record.
  • You want to search based on a field value rather than record position.
  • You need to build search functionality for file-based databases or archives.

Even though you loop sequentially, combining this logic with `ftell()` or `fseek()` lets you jump back to the found record for editing—making it an essential pattern when building interactive tools with random access files in C.

File Modes for Reading and Writing Random Access Files in C

When working with random access files in C, it’s crucial to choose the correct file mode for your operations. The file mode determines how the file is opened—whether for reading, writing, appending, or a combination of these—and whether the file is handled in text or binary format.

Here is the detailed table for file modes in random access files in C:

File Mode

Description

Access Type

File Existence Requirement

Example Usage

"r"

Opens the file for reading in text mode.

Read-only (text)

File must exist

Opening a text file for reading.

"w"

Opens the file for writing in text mode. Truncates the file to zero length.

Write-only (text)

File is created if it doesn't exist

Writing to a new or existing text file (overwrites the file).

"a"

Opens the file for appending in text mode. The file pointer is placed at the end.

Write-only (text)

File is created if it doesn't exist

Appending text to a file (without modifying existing content).

"r+"

Opens the file for both reading and writing in text mode.

Read/Write (text)

File must exist

Reading from and writing to an existing text file.

"w+"

Opens the file for both reading and writing in text mode. Truncates the file to zero length.

Read/Write (text)

File is created if it doesn't exist

Creating and modifying a text file (overwrites the file).

"a+"

Opens the file for both reading and appending in text mode. File pointer is placed at the end.

Read/Write (text)

File is created if it doesn't exist

Appending text and reading from a text file.

"rb"

Opens the file for reading in binary mode.

Read-only (binary)

File must exist

Opening a binary file for reading.

"wb"

Opens the file for writing in binary mode. Truncates the file to zero length.

Write-only (binary)

File is created if it doesn't exist

Writing to a new or existing binary file (overwrites the file).

"ab"

Opens the file for appending in binary mode. The file pointer is placed at the end.

Write-only (binary)

File is created if it doesn't exist

Appending data to a binary file (without modifying existing content).

"rb+"

Opens the file for both reading and writing in binary mode. File pointer is placed at the beginning.

Read/Write (binary)

File must exist

Modifying a binary file by reading and writing specific records.

"wb+"

Opens the file for both writing and reading in binary mode. Truncates the file to zero length.

Read/Write (binary)

File is created if it doesn't exist

Writing new data to a binary file and then reading it back.

"ab+"

Opens the file for both reading and appending in binary mode. File pointer is placed at the end.

Read/Write (binary)

File is created if it doesn't exist

Appending and reading from a binary file simultaneously.

"r+t"

Opens the file for reading in text mode. Same as "r" but explicit text mode.

Read-only (text)

File must exist

Opening a text file for reading.

"w+t"

Opens the file for writing in text mode. Truncates the file to zero length.

Write-only (text)

File is created if it doesn't exist

Writing to a new or existing text file (overwrites the file).

"a+t"

Opens the file for appending in text mode. The file pointer is placed at the end.

Write-only (text)

File is created if it doesn't exist

Appending text to a file (without modifying existing content).

"r+ t"

Opens the file for both reading and writing in text mode.

Read/Write (text)

File must exist

Reading from and writing to an existing text file.

"w+t+"

Opens the file for both reading and writing in text mode. Truncates the file to zero length.

Read/Write (text)

File is created if it doesn't exist

Creating and modifying a text file (overwrites the file).

"a+t+"

Opens the file for both reading and appending in text mode. File pointer is placed at the end.

Read/Write (text)

File is created if it doesn't exist

Appending text and reading from a text file.

File Mode Combinations for Random Access Files in C

Understanding how to combine file modes is crucial when working with random access files in C. These combinations let you perform different operations on the file while opening it in various modes, giving you flexibility and control. Whether you need to read, write, or append, selecting the right combination of file modes ensures that your program behaves as expected.

Common File Mode Combinations

Here are some of the most commonly used file mode combinations for random access files in C and their typical use cases:

File Mode Combination

Description

Access Type

File Existence Requirement

Use Case Example

"rb"

Opens a binary file for reading.

Read-only (binary)

File must exist

Opening a file to read binary data without modifying it.

"wb"

Opens a binary file for writing. The file is created if it doesn't exist or truncated if it exists.

Write-only (binary)

File is created if it doesn't exist

Creating or overwriting a binary file with new data.

"ab"

Opens a binary file for appending. The file pointer is placed at the end.

Write-only (binary)

File is created if it doesn't exist

Appending binary data to an existing file.

"rb+"

Opens a binary file for both reading and writing. The file pointer is placed at the beginning.

Read/Write (binary)

File must exist

Reading from and writing to an existing binary file.

"wb+"

Opens a binary file for both writing and reading. The file is created if it doesn't exist or truncated if it exists.

Read/Write (binary)

File is created if it doesn't exist

Creating a new binary file and then reading from and writing to it.

"ab+"

Opens a binary file for both appending and reading. The file pointer is placed at the end for writing.

Read/Write (binary)

File is created if it doesn't exist

Appending data to the end of the file while still being able to read from anywhere.

"r"

Opens a text file for reading.

Read-only (text)

File must exist

Opening a file to read text data.

"w"

Opens a text file for writing. The file is created if it doesn't exist or truncated if it exists.

Write-only (text)

File is created if it doesn't exist

Writing to a new or existing text file (overwrites existing content).

"a"

Opens a text file for appending. The file pointer is placed at the end.

Write-only (text)

File is created if it doesn't exist

Appending text data to a file.

"r+"

Opens a text file for both reading and writing.

Read/Write (text)

File must exist

Reading and writing to a text file.

"w+"

Opens a text file for both writing and reading. The file is truncated to zero length if it exists, or created if it doesn't.

Read/Write (text)

File is created if it doesn't exist

Overwriting a text file and performing both read and write operations.

"a+"

Opens a text file for both reading and appending. The file pointer is placed at the end.

Read/Write (text)

File is created if it doesn't exist

Appending and reading from a text file at the same time.

Conclusion 

In this blog, we've taken a deep dive into random access files in C and explored their vital role in efficient data handling. Random access files are essential when dealing with large datasets that need to be accessed directly, rather than sequentially. 

With functions like fseek(), ftell(), and rewind(), C gives you the power to navigate and manipulate files with precision, allowing for both faster and more flexible data processing. Understanding how to create, write, and read from random access files opens the door to developing more efficient programs, especially when working with structured data or files too large to fit into memory.

By mastering random access file types, functions, and file mode combinations, you can gain full control over your file operations, ensuring your programs perform optimally. Choosing the correct file mode and understanding how to manipulate file pointers lets you write more efficient code that handles complex file interactions with ease. 

Whether you’re updating records in a database, processing binary data, or appending to log files, understanding these core concepts will enhance your ability to work with files effectively in C. The ability to use random access files in C ensures that your programs can handle large files and datasets with greater speed and accuracy.

FAQs 

1. What are random access files in C?

Random access files in C allow you to read or write data at any position within the file without needing to process it sequentially. This is achieved by using functions like `fseek()` to move the file pointer to specific locations, making them ideal for tasks such as handling large records or databases.

2. How is random access different from sequential file access?

In random access, data can be read or written directly at any position in the file, whereas sequential access requires reading or writing data from the beginning to the end of the file. Random access is more efficient for operations that involve large datasets or require frequent updates to specific data points.

3. What is the purpose of file pointers in random access files?

File pointers in random access files allow you to keep track of the current position within the file. By moving the pointer using functions like `fseek()`, you can access any part of the file, whether it’s to read or write specific records, making it a powerful tool for manipulating large files efficiently.

4. Can you modify data in a random access file?

Yes, you can modify data in random access files by moving the file pointer to the desired location and overwriting the existing content. This capability makes random access files ideal for scenarios where you need to frequently update or modify records without rewriting the entire file.

5. How does the `fseek()` function affect file operations?

The `fseek()` function moves the file pointer to a specified location, enabling you to access different parts of the file directly. It can be used to skip over data, jump to the beginning or end, or seek to a specific offset, making it crucial for navigating and modifying data in random access files.

6. How does C handle large files with random access?

C handles large files in random access by allowing you to read and write data at specific positions within the file. This minimizes the need to load the entire file into memory, improving performance and enabling the efficient management of large datasets like databases or multimedia files.

7. What are the common file modes used with random access files?

Common file modes for random access files include `"r"`, `"w"`, `"a"`, `"rb"`, and `"wb"`. These modes determine how the file is opened (read, write, append) and whether it’s in binary or text format. Each mode impacts how you can interact with the file, whether modifying, reading, or appending data.

8. How do you read from a random access file?

To read from a random access file in C, you first move the file pointer to the desired position using `fseek()`. Then, use functions like `fread()` or `fscanf()` to read the data from that position. The flexibility of random access allows you to retrieve specific records without scanning the entire file.

9. Can I append data to a random access file?

Yes, you can append data to a random access file by opening it in append mode (`"a"` or `"ab"`), which positions the file pointer at the end. This ensures new data is added without modifying existing content. However, appending in random access files requires careful handling of file pointers to avoid overwriting.

10. What happens if I use `fseek()` incorrectly?

If `fseek()` is used incorrectly, it could result in the file pointer being positioned at an invalid location. This can lead to errors when reading or writing data, or it might cause data corruption. It’s important to ensure that the offset and origin parameters of `fseek()` are correctly set to valid values.

11. How do random access files improve performance?

Random access files improve performance by allowing direct access to specific data points in a file. This eliminates the need to process the file sequentially, making data retrieval and modification faster, especially for large files. Random access is particularly useful for applications like databases or systems where frequent updates to individual records are needed.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.