Random Access File In C

Types of Access files

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

  • Sequential Access
  • Random Access
  • Sequential Access

Reading data from the middle of a large file using sequential access is not the most efficient approach. In sequential file organization, data is stored continuously with each record following the other, allowing for sequential data access. This method involves reading data from the beginning of the file and processing it in the order it appears. Sequential access is best suited for applications that process data sequentially and do not require random access.

Random Access

A random access file in C allows us to read from or write to any part of the disk file without needing to process all preceding data sections. This type of file permits quick access to data for editing, deletion, or retrieval. Handling random access files in C involves similar open and close procedures as sequential files, albeit with the addition of a few extra functions.

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 position of the file pointer is with respect to the start of the file and can be identified using the ftell function.

Syntax:

It has the following syntax:

Example

ftell(FILE *fp)

To determine the position of the file pointer relative to the start of the file in C, you can employ the ftell function.

The following is the syntax for ftell:

Example

pos = ftell(FILE *fp);

Where ```

ftell(FILE *fp)

Example


Let's begin by examining a file named Jtp.txt containing the following details: Jtp is superior.

Program:

Let's examine the C code now:

include<stdio.h>

int main

{

FILE *fp;

fp=fopen("Jtp.txt","r");

if(!fp)

{

printf("Error: File cannot be opened\n") ;

return 0;

}

//Ftell will return 0 because the file pointer points to the beginning of the file.

printf("Position pointer in the beginning : %ld\n",ftell(fp));

char ch;

while(fread(&ch,sizeof(ch),1,fp)==1)

{

//Here, we go through the entire file and print everything up until the end.

printf("%c",ch);

}

printf("\nSize of file in bytes is : %ld\n",ftell(fp));

fclose(fp);

return 0;

}

Example


Output:

Position pointer in the beginning : 0

Jtp is best.

Size of file in bytes is : 9

Example


Explanation:

Initially, when the file pointer is positioned at the start, the ftell function returns 0. Subsequently, after reading through the entire file content, the ftell function now returns 9, reflecting the total size of the file.

### How to utilize C's rewind() function:

The rewind() function is utilized to reset the file pointer back to the beginning of the file. This function is beneficial when there is a need to modify a file.

Syntax:

It has the following syntax:

rewind(FILE *fp);

Example


In this scenario, fp represents a file pointer of the FILE data type. To understand the rewind() function, let's examine the program provided below:

Program:

include<stdio.h>

int main

{

FILE *fp;

fp = fopen("Jtp.txt","r");

if(!fp)

{

printf("Error in opening file\n");

return 0;

}

//The file pointer always starts at the beginning of the file.

printf("Position of the pointer : %ld\n",ftell(fp));

char ch;

while(fread(&ch,sizeof(ch),1,fp)==1)

{

//Here, we go through the entire file and print everything we find till we get to the finish.

printf("%c",ch);

}

printf("Position of the pointer : %ld\n",ftell(fp));

//It will return to its previous location below using the rewind function.

rewind(fp);

printf("Position of the pointer : %ld\n",ftell(fp));

fclose(fp);

return 0;

}

Example


Output:

Position of the pointer : 0

Jtp is best.

Position of the pointer : 9

Position of the pointer : 0

Example


Explanation:

In this instance, the initial call to ftell results in 0 as the pointer is positioned at the file's beginning. Subsequent use of ftell, after navigating the file, returns 17, representing the file's size. Upon invoking rewind(fp), the pointer reverts to its original position, 0. Consequently, the final ftell operation also indicates 0.

### How to utilize C's fseek() function:

The fseek() function is employed to reposition the file pointer to a specified location within the file.

Syntax:

The syntax is:

int fseek(FILE *fp, long displacement, int origin);

Example


The various components are as follows:

fp - file pointer .

The term "displacement" refers to the amount of bytes that are either skipped forward or backward from the position of the third argument. This extended integer can have two potential values: positive or negative.

It is the location where something is related to a shift. The trio of values listed below are the ones that will be recognized.

| 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)thbyte of the file. |
| fseek(fp, N, 1) | It advances our position in the file byN bytesfrom where we are at the moment. |
| fseek(fp, -N, 1) | It moves usN bytes backwardin 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 :

include<stdio.h>

int main

{

FILE *fp;

fp = fopen("jtp.txt","r");

if(!fp)

{

printf("Error: File cannot be opened\n");

return 0;

}

//Move 3 bytes forward, so if we print all the way through, we won't see the first 6 bytes.

fseek(fp, 3, 0);

char ch;

while(fread(&ch,sizeof(ch),1,fp)==1)

{

//Here, we go through the entire file and print everything up until the end.

printf("%c",ch);

}

fclose(fp);

return 0;

}

Example


Output:

Is best.

Example


Explanation:

When navigating through the file in that location, the result is remarkable. It becomes evident that executing fseek(fp,6,0) causes the cursor to position itself at the 7th byte within the file, which is 6 bytes ahead from the starting point.

### Identify a Particular Record in a File:

If we know the size of the record and its starting position in the file, we can employ the fseek() function to pinpoint it. To retrieve a specific record from the data file, it is crucial to have a clear understanding of two key aspects:

- The exact location where the data commences within the file.

- The precise size of the data:

Since we are aware of the length of the record, we can utilize the fseek() function to move the file pointer to the starting position of the record and another pointer to its ending position.

### Reading and writing files in different file modes:

The individual characters "r", "b", "w", "a", and "+" are merged with other characters to generate various file mode descriptors, which are employed for file input and output operations.

When initiating the opening of a file, you determine the mode of operation, such as whether it should be opened for appending or created anew, whether it should be handled as text or binary data, and if it should be read from or written to. The letters "r", "b", "w", "a", and "+" are combined with other letters to form various file mode options, which dictate the behavior. Let's delve into these specifications now:

It provides access to view the file. If the file is not present or cannot be located, the operation will not succeed.

It signifies the creation of a fresh or blank file for writing purposes. Any existing data within the file will be erased during this operation.

If the file does not yet exist, it will be generated before being opened for writing at the end (appending) without erasing the EOF indicator.

We can introduce three additional modes by adding "+" to the file mode:

It allows for both reading data from and writing data to the file.

Consequently, the file is initialized as empty and available for both writing and reading operations. Any existing data within the file will be erased.

It enables the file to be accessed for reading and appending purposes. When adding new content, the EOF indicator needs to be eliminated before appending data and then reinstated after the writing operation is completed. If the file is not already present, it will be created initially.

### Combinations of File Mode

Combinations of File Mode allow for concurrent reading and writing operations. In most cases, a text file can only be read or written sequentially. However, a binary file supports concurrent reading and writing. The following table details the capabilities of each combination:

| 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 is not yet present, it can be generated by utilizing functions such as fopen(). This process is illustrated in the example below:

Program:

include <stdio.h>

int main {

char ch;

// file pointer

FILE *fp;

// open and create file in write mode if it does not exist.

fp = fopen("char.txt", "w");

if (fp != NULL) {

printf("File created successfully!\n");

fclose(fp); // Closing the file after creation is a good practice.

} else {

printf("Failed to create the file.\n");

return 0;

}

return 0;

}

Example


Output:

File created successfully!

Example


### Randomly Writing Data to a Random-Access File:

The data written by the program is stored in the "student.txt" file. This process involves using a combination of fseek() and fwrite() functions to specify where the data should be saved within the file. The fseek() function is responsible for positioning the file pointer to a particular location in the file, while fwrite() is then used to write the data to that specific location. Below is an example of how this is implemented in code:

Program:

include <stdio.h>

// Definition of student structure

struct Student {

char name[20]; // student name

int roll_number; // roll number

};

int main

{

FILE *fp; // file pointer

// The line that follows creates a student object with default settings.

struct Student s = {"", 0};

// In the event that the file cannot be opened, fopen exits.

if (!(fp = fopen( "student.txt", "r+" )))

{

printf("File cannot be opened.");

return 0;

}

// Information that the user enters will be copied to the file

while(1)

{

//requesting the user to provide their roll number

printf("Enter roll number from (1 to 100) , -1 to end input : ");

scanf("%d",&s.roll_number);

if(s.roll_number == -1)

break;

// requesting the user to enter their name

printf("Enter name : ");

scanf("%s",s.name);

fseek(fp,(s.roll_number-1)*sizeof(s),0);

fwrite(&s, sizeof(s), 1, fp);

}

fclose(fp); // Fclose terminates the file.

return 0;

}

Example


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

Example


## Conclusion:

- 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.

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

- The file pointer can be moved to the file's beginning using the rewind() function .

- The file position is moved to the appropriate point using the fseek() function .

- 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.

- 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.

- Combinations of File Mode enable simultaneous reading and writing operations.

Input Required

This code uses input(). Please provide values below: