top

Search

C Tutorial

.

UpGrad

C Tutorial

Random Access Files in C

Introduction

Random access files are essential to computer programming since they are required for data processing. By offering the capacity to read from and write to specific file sections, they offer efficient data management. In this blog article, we will go deeper into the concept of random access files in the C programming language. We'll explore many functions and random access files in the C examples of how to edit random access files. Let's begin our voyage without further ado!

Overview

Random access files provide a robust mechanism for effectively manipulating data in the C programming language. In contrast to sequential access files, which limit data operations to sequential reading or writing, random access files allow direct access to specific positions within the file. This unique capability empowers us to perform various operations, including updating, inserting, or deleting data at any desired location within the file.

How to use the ftell() function in C?

The ftell() function in C provides the current file position indicator, which denotes the offset from the beginning of the file. It plays a vital role when working with random access files as it aids in determining the current position within the file. This function returns a long integer value, which serves as a means to track the file's current position during file operations.

By employing the ftell() function, you can obtain the current position in the file and utilize it for subsequent tasks like fseek() or data retrieval. This function proves particularly valuable when you need to remember a specific position within a file for future references or updates.

Example: 

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("prepbytes.txt","r");
    if(!fp) 
    {
        printf("Error: File cannot be opened\n") ;
        return 0;
    }
        printf("Position pointer in the beginning : %ld\n",ftell(fp));  
    char ch;
    while(fread(&ch,sizeof(ch),1,fp)==2)
    {
        printf("%c",ch);
    }
    printf("\nSize of file in bytes is : %ld\n",ftell(fp));
    fclose(fp);
    return 0;
}

How to use the rewind() function in C?

The ftell() function in C returns the current file position indicator, which represents the offset from the beginning of the file. When working with random access files, it is crucial to have this capability since it aids in figuring out where you are in the file right now. In order to maintain track of the file's current location while performing file operations, the ftell() method produces a long integer.

When you need to keep track of a certain location inside a file for revisions or future references, this capability is extremely helpful. You may obtain the current location in the file using the ftell() function and use it for further actions like fseek() or data retrieval. 

Example: 

#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("prepbytes.txt","r");
    if(!fp)
    {
        printf("Error in opening file\n");
        return 0;
    }
    printf("Position of the pointer : %ld\n",ftell(fp));
    char ch;
    while(fread(&ch,sizeof(ch),1,fp)==2)
    {        printf("%c",ch);
    }
    printf("Position of the pointer : %ld\n",ftell(fp));
    rewind(fp);
    printf("Position of the pointer : %ld\n",ftell(fp)); 
    fclose(fp);
    return 0;
}

How to use the fseek() function in C?

The fseek() function allows us to set the file position indicator to a specific location within the file. It provides precise control over file navigation, enabling you to move the position indicator to any desired offset within the file. The fseek() function takes three arguments: the file pointer, the offset, and the reference point.

By utilizing fseek(), you gain the ability to efficiently navigate to any desired offset within the file. This functionality opens up a wide range of file operations, including reading or writing data, providing flexibility and control in working with files. 

Example:

#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("prepbytes.txt","r");
    if(!fp)
    {
        printf("Error: File cannot be opened\n");
        return 0;
    }
    fseek(fp, 6, 0);
    char ch;
    while(fread(&ch,sizeof(ch),1,fp)==2)
    {
        printf("%c",ch);
    }
    fclose(fp);
    return 0;
}

Find a Specific Record in a File

Searching for a specific record within a random access file involves reading each document sequentially until the desired record is found or the end of the file is reached. This process typically requires a loop to iterate through the records and compare the data with the search criteria.

By utilizing fseek() and fread(), you can read each record from the file and compare it with the desired criteria. If a match is found, you can perform specific actions or retrieve the data as needed. It's essential to handle scenarios where the desired record is not found or the end of the file is reached to ensure proper program execution.

File Modes for Reading and Writing Files

When dealing with files in C, it is vital to have a clear comprehension of the diverse file modes that govern the permissible operations on the file. These file modes determine whether the file is opened for reading, writing, or both, and also determine the position of the file pointer during file operations.

Some common file modes include:

File Mode

Description

"r"

Signifies reading a file.

"w"

Opens a file for writing. The file will be shortened if it already exists. If not, a new file is created.

"a"

Opens a file for appending, allowing writing at the end of the file. If the file does not exist, a new file is created.

"r "

Initializes the file with the file pointer at the beginning and opens it for both reading and writing.

File Mode Combinations

In addition to individual file modes, combining file modes to perform specific operations on random access files is possible. Some common file mode combinations include:

File Mode

Description

"w "

Opens the file for reading and writing. If the file already exists, it will be truncated; otherwise, a new file will be created.

"a "

Opens the file for reading and appending. If the file doesn't already exist, a new file will be created.

"r "

Opens the file for reading and writing, starting with the file pointer at the beginning.

Each file mode combination has its own behavior regarding reading and writing operations. Understanding these combinations allows you to choose the appropriate mode for your specific needs.

Creating a Random-Access File

There are a series of instructions that must be carefully followed in order to construct a random-access file. To begin with, open the file in the specified mode by using the fopen() function. Once the file has been properly opened, you can quickly put the necessary data into it using the fwrite() method. The fwrite() function streamlines the sequential writing process by offering an effective and efficient method. It's crucial to remember that fwrite() makes sure data is written to the file sequentially. Finally, after the writing operation is over, it is critical to shut the file using the fclose() method in order to preserve correct resource management and avoid any potential problems. You can efficiently and successfully use these organized methods if you rigorously follow them.

Writing Data Randomly to a Random-Access File

Random access files' ability to write data at particular points inside the file is one of its key benefits. Data updates or insertions at any desired point can be accomplished by combining the fseek() and fwrite() routines.

First, use fseek() to travel to the appropriate point within the file before writing data arbitrarily. The data is then written to that place using fwrite(). You may make sure that the data is stored at the required place without overwriting old data by changing the file position indication with fseek().

This gives you fine-grained control over the placement of the new data within the file. Finally, as a crucial step for resource management, remember to close the file using the fclose() function after completing the writing process. By diligently following these systematic steps, you can effectively create a random-access file while maintaining data integrity and organization.

Conclusion

Random access files offer a flexible and efficient way to work with data in the C programming language. Understanding how to utilize functions like ftell(), rewind(), and fseek() enables us to work with files more effectively. We have explored various techniques to read, write, search, and modify data in random access files. 

In this comprehensive guide, we have explored the concept of random access files in the C programming language. We have delved into various functions and techniques that allow efficient data manipulation within files. By understanding random access files, developers can take advantage of precise control over file navigation, enabling them to perform operations such as updating, inserting, or deleting data at any desired location within the file.

FAQs

1. How can the ftell() function be used in C when working with random access files?

The current file position indication, which denotes the offset from the file's beginning, is returned by the ftell() function in the C language. It may be used in combination with other file operations like fseek() or data retrieval and is helpful for locating the current place inside the file.

2. What are random access files in the context of computer programming?

Random access files refer to files that allow direct access to specific positions within the file for efficient data manipulation. Unlike sequential access files, random access files enable operations like updating, inserting, or deleting data at any desired location within the file.

3. Can I use random access files in languages other than C?

While the concept of random access files exists in other programming languages, the implementation and specific functions may vary. However, the underlying principle of accessing specific positions within a file remains the same.

4. How does the fseek() function work in C and what is its role in random access file operations?

The fseek() function allows you to set the file position indicator to a specific location within the file. It provides precise control over file navigation by specifying the offset from a reference point. This function is essential for moving the position indicator to a desired offset, enabling various file operations such as reading or writing data.

5. How do I handle errors while working with random access files?

It's crucial to manage various mistakes that might happen while dealing with random access files. This involves looking for read/write problems, end-of-file circumstances, and file open failures. Proper error handling ensures that your program responds appropriately to exceptional situations and maintains data integrity.

Leave a Reply

Your email address will not be published. Required fields are marked *