Random Access File in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

This article delves into random file access in C, enabling direct data reading or writing without processing all preceding data. Distinct from sequential access, it offers enhanced flexibility for data manipulation. Random access, ideal for large files, involves functions like ftell(), fseek(), and rewind(). This method, akin to choosing a song on a CD, requires more coding but offers superior efficiency and flexibility in file handling.

random access to a file

How to use the ftell() function in C

Highlights:

  1. ftell() is used to find the position of the file pointer from the starting of the file.
  2. 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:

  1. rewind() is used to move the file pointer to the beginning of the file.
  2. 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:

  1. The fseek() function moves the file position to the desired location.
  2. 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.
ConstantValuePosition
SEEK_SET0Beginning of file
SEEK_CURRENT1Current position
SEEK_END2End of file

Here is the list of common operations that we can perform using the fseek() function.

OperationDescription
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:

CombinationType of FileOperation
rtextread
rb+binaryread
r+textread, write
r+bbinaryread, write
rb+binaryread, write
wtextwrite, create, truncate
wbbinarywrite, create, truncate
w+textread, write, create, truncate
w+bbinaryread, write, create, truncate
wb+binaryread, write, create, truncate
atextwrite, create
abbinarywrite, create
a+textread, write, create
a+bbinarywrite, create
ab+binarywrite, 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

  1. 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.
  2. ftell() is used to find the position of the file pointer from the starting of the file.
  3. rewind() is used to move the file pointer to the beginning of the file.
  4. The fseek() function moves the file position to the desired location.
  5. 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.
  6. 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.
  7. File Mode combinations allow us to simultaneously accomplish reading and writing operations.