Random Access to a File
Learn via video course

Overview
In this article, we will be going over random access to a file. Random access file in C enables us to read or write any data in our disk file without reading or writing every piece of data before it. In a random-access file, we may quickly search for data, edit it or even remove it. We can open and close random access files in C, same as sequential files with the same opening mode, but we need a few new functions to access files randomly. This extra effort pays off flexibility, power, and disk access speed. Random access to a file in C is carried with the help of functions like ftell(), fseek() and rewind().
Scope
- This article introduces random access files in C.
- It discusses the various functions like ftell(), fseek() and rewind() which aid random file access.
- It goes over the methods of reading and writing from a file using file modes and their various combinations.
- It covers creating and writing data randomly to a file.
Introduction
In C, the data stored in a file can be accessed in the following ways:
- Sequential Access
- Random Access
If the file size is too huge, sequential access is not the best option for reading the record in the middle of the file. Random access to a file can be employed in this situation, enabling access to any record at any point in the file. We can imagine data in a random access file as songs on a compact disc or record; we can fast forward directly to any song we want without playing the other pieces. We can do so if we're playing the first song, the sixth song, the fourth song. This order has nothing to do with the songs' order initially recorded. Random file access sometimes takes more programming but rewards our effort with a more flexible file-access method. Thus, there are three functions which help in using the random access file in C:
- fseek()
- ftell()
- rewind()
How to use the ftell() function in C
Highlights:
- ftell() is used to find the position of the file pointer from the starting of the file.
- Its syntax is as follows:
In C, the function ftell() is used to determine the file pointer's location relative to the file's beginning. ftell() has the following syntax:
Where fp is a file pointer and pos holds the current position i.e., total bytes read (or written). For Example: If a file has 20 bytes of data and if the ftell() function returns 5 it means that 5 bytes have already been read (or written). Consider the below program to understand the ftell() function:
First, let us consider a file - Scaler.txt which contains the following data:
Scaler is amazing
Now let us see the code in C:
Output:
We can observe that in the beginning, ftell returns 0 as the pointer points to the beginning and after traversing completely we print each character of the file till the end, and now ftell returns 17 as it is the size of the file.
How to use the rewind() function in C
Highlights:
- rewind() is used to move the file pointer to the beginning of the file.
- Its syntax is as follows:
The file pointer is moved to the beginning of the file using this function. It comes in handy when we need to update a file. The following is the syntax:
Here, fp is a file pointer of type FILE. Consider the following program to understand the rewind() function:
Output:
We can observe that firstly when ftell is called, it returns 0 as the position of the pointer is at the beginning, and then after traversing the file, when ftell is called, 17 is returned, which is the size of the file. Now when rewind(fp) is called, the pointer will move to its original position, which is 0. So last ftell returns 0.
How to use the fseek() function in C
Highlights:
- The fseek() function moves the file position to the desired location.
- Its syntax is:
To shift the file position to a specified place, use the fseek() function.
Syntax:
The various components are as follows:
- fp – file pointer.
- displacement - represents the number of bytes skipped backwards or forwards from the third argument's location. It's a long integer that can be either positive or negative.
- origin – It's the location relative to the displacement. It accepts one of the three values listed below.
Constant | Value | Position |
---|---|---|
SEEK_SET | 0 | Beginning of file |
SEEK_CURRENT | 1 | Current position |
SEEK_END | 2 | End of file |
Here is the list of common operations that we can perform using the fseek() function.
Operation | Description |
---|---|
fseek(fp, 0, 0) | This takes us to the beginning of the file. |
fseek(fp, 0, 2) | This takes us to the end of the file. |
fseek(fp, N, 0) | This takes us to (N + 1)th bytes in the file. |
fseek(fp, N, 1) | This takes us N bytes forward from the current position in the file. |
fseek(fp, -N, 1) | This takes us N bytes backward from the current position in the file. |
fseek(fp, -N, 2) | This takes us N bytes backward from the end position in the file. |
Let us see the below program to understand the fseek() function:
Output:
We can observe that when fseek(fp,6,0) the pointer moves to the 7th byte in the file, or we can say 6 bytes forward from the beginning, So when we traverse the file from that position, we receive output as is amazing.
Find a Specific Record in a File
Highlights:
fseek() function can be used to find a specific record in a file provided we already know where the record starts in the file and its size.
To fetch any specified record from the data file, the knowledge of two things are essential:
- Where the data starts in the file.
- Size of the data
We could first use fseek() to move the file pointer to where the record starts from, and another pointer using fseek() to where the record ends as we already know the size of the record.
File Modes for Reading and Writing Files
Highlights:
Reading and writing to files is accomplished by combining the single letters "r", "b", "w", "a", and "+" with the other letters to form one or more file mode specifiers.
When you open a file, you define how it should be opened: whether it should be created from scratch or overwritten, whether it should be text or binary, read or write, and if it should be appended to. This is accomplished by combining the single letters "r", "b", "w", "a", and "+" with the other letters to form one or more file mode specifiers. Let us take a look at them:
- r - Allows you to read the file. This will fail if the file does not exist or cannot be located.
- w - Creates a new, empty file for writing. The data in the file is deleted if it exists.
- a - This opens the file for writing at the end (appending) without removing the EOF marker before adding new data to it; if the file doesn't exist, this creates it first.
Appending "+" to the file mode allows us to create three new modes:
- r+ - Allows you to read and write to the file. (There must be a file.)
- w+ - This opens the file as an empty one that can be read and written. The data in the file is deleted if it exists.
- a+ - This opens the file for reading and appending; the adding procedure includes clearing the EOF marker before documenting new data to the file and restoring it after writing is complete. If the file does not exist, it is created first.
File Mode Combinations
Highlights:
File Mode combinations allow us to accomplish reading and writing operations simultaneously.
In general, you can only read from or write to a text file, not simultaneously. A binary file allows you to read and write to the same file. What you can accomplish with each combination is shown in the table below:
Combination | Type of File | Operation |
---|---|---|
r | text | read |
rb+ | binary | read |
r+ | text | read, write |
r+b | binary | read, write |
rb+ | binary | read, write |
w | text | write, create, truncate |
wb | binary | write, create, truncate |
w+ | text | read, write, create, truncate |
w+b | binary | read, write, create, truncate |
wb+ | binary | read, write, create, truncate |
a | text | write, create |
ab | binary | write, create |
a+ | text | read, write, create |
a+b | binary | write, create |
ab+ | binary | write, create |
Creating a Random-Access File
Highlights:
Functions like fopen() can be used to create files if they do not exist.
Functions like fopen() can be used to create files if they do not exist. This can be seen in the example below:
Writing Data Randomly to a Random-Access File
The program writes data to the file "student.txt". It stores data at precise points in the file using a mix of fseek() and fwrite(). The file position pointer is set to a given place in the file by fseek(), and then the data is written by fwrite(). Let us see the code below:
Output:
Summary
- Random access file in C enables us to read or write any data in our disk file without reading or writing every piece of data before it.
- ftell() is used to find the position of the file pointer from the starting of the file.
- rewind() is used to move the file pointer to the beginning of the file.
- The fseek() function moves the file position to the desired location.
- fseek() function can be used to find a specific record in a file provided we already know where the record starts in the file and its size.
- Reading and writing to files are accomplished by combining the single letters "r", "b", "w", "a", and "+" with the other letters to form one or more file mode specifiers.
- File Mode combinations allow us to simultaneously accomplish reading and writing operations.