Javatpoint Logo
Javatpoint Logo

Random Access File in C

Introduction:

In this article, we'll talk about random file access. The C language's random access file enable us to read or write any data in the disk file without first reading or writing all the data that came before it. We can easily look for data in a random-access file, edit it, or even delete it. Random access files can be opened and closed using the same opening way as sequential files in C programming. Although, the random access files require a few unique functions. Flexibility, power, w, and disk access speed are the benefits of this extra exertion. Random access to a file can be carried out in C with the aid of functions like ftell(), fseek(), and rewind().

Types of Access files

The following methods exist in C for accessing data that is saved in a file:

  1. Sequential Access
  2. Random Access

Sequential Access

Sequential access is not the optimum method for reading the data in the centre of the file if the file size is too large. A sequential file is a kind of file organization in which we can keep the data continuously, and every record is stored after the other and can be accessed the data sequentially. In this file, the data is read from the start of the file and processed in the sequence it comes in the file. It is mainly suitable for those applications where the data is processed sequentially and doesn't access randomly.

Random Access

A random access file in C is a kind of file that enables us to write or read any data in the disk file without having to read or write each section of data before it. In this file, we may instantly find for data, modify it, or even delete or remove it. We may open and close random access files in C in the same way we can sequential files, but we require a few more functions to do so.

Functions of Random Access file

Consequently, there are mainly three functions that assist in accessing the random access file in C:

  • ftell()
  • rewind()
  • fseek()

How to employ C's ftell() function:

The file pointer's position is relative to the file's beginning and can be determined using the ftell() function.

Syntax:

It has the following syntax:

To find the file pointer's position about the file's beginning in C, use the ftell() function.

The following is the syntax for ftell():

Where pos contain the current position or the total number of bytes read (or written), and fp is a file pointer. As an illustration, if the ftell() function returns 5 when a file has 20 bytes of data, 5 bytes have already been read (or written). Consider the following program to comprehend the ftell() function:

Let's start by looking at a file called Jtp.txt that has the following information in it: Jtp is best.

Program:

Let's examine the C code now:

Output:

Position pointer in the beginning : 0
Jtp is best.
Size of file in bytes is : 9

Explanation:

We can see that at first, ftell returns 0 since the pointer points to the beginning, and that once we have printed every character of the file up until the end, ftell now returns 9 because that is the file's size.

How to utilize C's rewind() function:

The file pointer can be moved to the file's beginning using the rewind() function. When a file needs to be updated, it is useful.

Syntax:

It has the following syntax:

In this case, fp is a file pointer of the FILE type. To comprehend the rewind() method, take a look at the following program:

Program:

Output:

Position of the pointer : 0
Jtp is best.
Position of the pointer : 9
Position of the pointer : 0

Explanation:

In this example, we can see that the first time ftell is called, it returns 0 since the pointer is at the starting of the file, and the second time ftell is called after traversing the file, it returns 17, which is the file's size. Now, the pointer will return to its initial location, which is 0, when rewind(fp) is invoked. Last ftell therefore yields 0.

How to utilize C's fseek() function:

The fseek() function is used to move the file position to a given location.

Syntax:

The syntax is:

The various components are as follows:

fp - file pointer.

displacement - It indicates the number of bytes skipped from the third argument's location either backward or forward. This long integer has two possible values: positive and negative.

origin - It is where something is about a displacement. The three values stated below are the ones it will accept.

Constant Value Position
SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of file

The list of typical operations that we can carry out with the fseek() function is provided below.

Operation Description
fseek(fp, 0, 0) It brings us to the file's beginning.
fseek(fp, 0, 2) This brings us to the file's conclusion.
fseek(fp, N, 0) Now, we are on the (N + 1)th byte of the file.
fseek(fp, N, 1) It advances our position in the file by N bytes from where we are at the moment.
fseek(fp, -N, 1) It moves us N bytes backward in the file from where we are right now.
fseek(fp, -N, 2) It moves us N bytes away from the file's final position.

Let's look at the following program to better understand the fseek() method:

Output:

Is best.

Explanation:

When we traverse the file from that place, we get an astounding output. We can see that when we call fseek(fp,6,0), the pointer goes to the 7th byte in the file or 6 bytes forward from the beginning.

Identify a Particular Record in a File:

If we are aware of the record's size and where it begins in the file, we may use the fseek() method to locate it. Two things must be understood to fetch any desired record from the data file:

  1. Where in the file the data begins.
  2. The size of the data:

Since we already know the record's length, we may use fseek() to relocate the file pointer to where the record begins and another pointer to where it ends.

Reading and writing files in different file modes:

The single letters "r", "b", "w", "a", and "+" are combined with the other letters to produce multiple file mode specifiers, which are used to read and write files.

When opening a file, you specify how it should be opened, including whether it should be appended to or created from scratch, whether it should be text or binary, and if it should be read or written. The single letters "r", "b", "w", "a", and "+" are combined with the other letters to produce one or more file mode specifiers, which is how this is done. Let's look at them now:

r -

It gives you access to read the file. If the file is missing or cannot be found, it will fail.

w -

It indicates that a new or empty file is created for writing. If there is any data in the file, it will be destroyed.

a-

If the file doesn't already exist, it creates it first before opening it for writing at the end (appending) without deleting the EOF marker.

We may add three further modes by appending "+" to the file mode:

r+ -

It enables both reading from and writing to the file.

w+ -

As a result, the file is opened as empty and ready for writing and reading. If there is any data in the file, it will be destroyed.

a+ -

It makes the file accessible for reading and appending. During the adding process, the EOF marker must be removed before adding new data to the file and restored after the writing is finished. The file is first generated if it doesn't already exist.

Combinations of File Mode

Combinations of File Mode enable simultaneous reading and writing operations. Generally speaking, you can only read or write a text file one at a time. A binary file enables simultaneous reading and writing. The table below outlines what each combo is capable of:

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

How to create a random access file:

If a file doesn't already exist, it can be created using functions like fopen(). It is demonstrated in the following example:

Program:

Output:

File created successfully!

Randomly Writing Data to a Random-Access File:

The "student.txt" file receives data written by the program. It utilizes a combination of fseek() and fwrite() to save data in the file at specific locations. Fseek() sets the file position pointer to a certain location in the file, and fwrite() subsequently writes the contents to the file. Take a look at the code below:

Program:

Output:

Enter roll number from (1 to 100) , -1 to end input : 1
Enter name :Jtp
Enter roll number from (1 to 100) , -1 to end input : 10
Enter name : Suman
Enter roll number from (1 to 100) , -1 to end input : -1

Conclusion:

  1. In random access file, we can read or write any data in our disk file in C without first reading or writing all the data that came before it.
  2. The file pointer's position is relative to the file's beginning and can be determined using the ftell() function.
  3. The file pointer can be moved to the file's beginning using the rewind() function.
  4. The file position is moved to the appropriate point using the fseek() function.
  5. If we are aware of the record's size and where it begins in the file, we may use the fseek() method to locate it.
  6. The single letters "r", "b", "w", "a", and "+" are combined with the other letters to produce multiple file mode specifiers, which are used to read and write to files.
  7. Combinations of File Mode enable simultaneous reading and writing operations.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA