For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
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.
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.
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:
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:
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:
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:
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.
Purpose: Moves the file pointer to a specified location.
Use in random access: Crucial for jumping to a specific byte position in the file.
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.
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.
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.
Purpose: Closes an open file.
Use in random access: Ensures all buffers are flushed and resources are released.
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.
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
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.
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
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.
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.
long ftell(FILE *stream);
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
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.
When dealing with random access files in C, `ftell()` is incredibly useful for:
In combination with `fseek()`, `ftell()` gives you complete control over file navigation, which is what makes random access files in C so powerful.
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.
void rewind(FILE *stream);
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
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.
In the context of random access files in C, `rewind()` is useful for:
It’s a simple yet effective tool that complements functions like `fseek()` and `ftell()` for complete control over file navigation.
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.
int fseek(FILE *stream, long offset, int origin);
Constants for `origin`
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
Output
Third Record: ID = 3, Name = Record 3
In random access files in C, `fseek()` is essential when:
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.
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
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.
This search approach is helpful when:
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.
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. |
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.
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. |
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.