Functions of Random Access File
Random access files in C provide a set of functions that allow you to perform various operations on the file. Let’s look at some of the key functions used for random access:
1. fopen(): This function is used to open a file. It takes two arguments: the name of the file & the mode in which the file should be opened (e.g., "r" for read mode, "w" for write mode, "a" for append mode, etc.).
2. fclose(): This function is used to close a file that was previously opened using fopen(). It takes the file pointer as an argument & ensures that any data written to the file is properly saved.
3. fseek(): This function is used to move the file pointer to a specific position in the file. It takes three arguments: the file pointer, the number of bytes to move the pointer, & the reference position (e.g., SEEK_SET for the beginning of the file, SEEK_CUR for the current position, SEEK_END for the end of the file).
4. ftell(): This function returns the current position of the file pointer. It takes the file pointer as an argument & returns a long integer representing the number of bytes from the beginning of the file.
5. rewind(): This function moves the file pointer to the beginning of the file. It takes the file pointer as an argument & is equivalent to calling fseek() with a position of 0 & SEEK_SET as the reference.
6. fread(): This function is used to read data from a file. It takes four arguments: a pointer to the buffer where the data will be stored, the size of each element to be read, the number of elements to be read, & the file pointer.
7. fwrite(): This function is used to write data to a file. It takes four arguments: a pointer to the buffer containing the data to be written, the size of each element to be written, the number of elements to be written, & the file pointer.
Creating a Random-Access File
To create a random-access file in C, you need to follow below mentioned steps:
1. Declare a file pointer variable of type FILE*.
2. Open the file using the fopen() function, specifying the file name & the appropriate mode. For creating a new file, use the "w" mode, & for opening an existing file, use the "r+" mode.
3. If the file is opened successfully, you can start writing data to the file using functions like fwrite() or fprintf().
4. After writing the data, close the file using the fclose() function to ensure that all the data is properly saved.
For example :
#include <stdio.h>
typedef struct {
int id;
char name[50];
} Student;
int main() {
FILE *file;
Student student;
// Open the file in write mode
file = fopen("students.dat", "w");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Get student details from the user
printf("Enter student ID: ");
scanf("%d", &student.id);
printf("Enter student name: ");
scanf("%s", student.name);
// Write the student record to the file
fwrite(&student, sizeof(Student), 1, file);
// Close the file
fclose(file);
printf("Student record created successfully.\n");
return 0;
}
In this example, we define a Student structure that represents a student record with an ID & a name. We open a file named "students.dat" in write mode using fopen(). If the file is opened successfully, we prompt the user to enter the student details & then write the student record to the file using fwrite(). Finally, we close the file using fclose().
This code creates a new file named "students.dat" & writes a single student record to it. You can modify the code to write multiple records or to read the records back from the file.
Writing Data Randomly to a Random-Access File
One of the key advantages of random-access files is the ability to write data at any position in the file. To write data randomly, you need to use the fseek() function to move the file pointer to the desired position before writing the data.
For example :
#include <stdio.h>
typedef struct {
int id;
char name[50];
float grade;
} Student;
int main() {
FILE *file;
Student student;
int studentId, recordNum;
// Open the file in read-write mode
file = fopen("students.dat", "r+");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Get the student ID from the user
printf("Enter student ID: ");
scanf("%d", &studentId);
// Calculate the record number based on the student ID
recordNum = studentId - 1;
// Move the file pointer to the desired record
fseek(file, recordNum * sizeof(Student), SEEK_SET);
// Read the existing student record
fread(&student, sizeof(Student), 1, file);
// Update the student's grade
printf("Enter new grade for student %d: ", studentId);
scanf("%f", &student.grade);
// Move the file pointer back to the beginning of the record
fseek(file, recordNum * sizeof(Student), SEEK_SET);
// Write the updated student record back to the file
fwrite(&student, sizeof(Student), 1, file);
// Close the file
fclose(file);
printf("Student record updated successfully.\n");
return 0;
}
- In this example, we assume that we have a file named "students.dat" that contains student records. Each record consists of a student ID, name, & grade. We open the file in read-write mode using "r+" mode in fopen().
- To write data randomly, we prompt the user to enter a student ID. We then calculate the record number based on the student ID (assuming that student IDs start from 1). We use fseek() to move the file pointer to the desired record position by multiplying the record number by the size of the Student structure.
- After moving the file pointer, we read the existing student record using fread(). We prompt the user to enter a new grade for the student & update the grade in the student record. Then, we move the file pointer back to the beginning of the record using fseek() again.
- Finally, we write the updated student record back to the file using fwrite() at the same position. We close the file using fclose().
How to Use the rewind() Function in C
The rewind() function in C is used to move the file pointer to the beginning of a file. It is a convenient way to reset the file pointer to the starting position, allowing you to read or write from the beginning of the file again.
For example :
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
// Open the file in read mode
file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Read the first line from the file
fgets(buffer, sizeof(buffer), file);
printf("First line: %s", buffer);
// Move the file pointer to the beginning of the file
rewind(file);
// Read the first line again
fgets(buffer, sizeof(buffer), file);
printf("First line after rewind: %s", buffer);
// Close the file
fclose(file);
return 0;
}
- In this example, we have a file named "data.txt" that contains some text data. We open the file in read mode using fopen() with the "r" mode.
- We use fgets() to read the first line from the file & print it. After reading the first line, the file pointer is positioned at the beginning of the second line.
- To move the file pointer back to the beginning of the file, we use the rewind() function. It takes the file pointer as an argument & repositions the pointer to the start of the file.
- After calling rewind(), we read the first line again using fgets() & print it. This time, we get the same first line as before because the file pointer is back at the beginning of the file.
- Finally, we close the file using fclose().
Note: The rewind() function is useful when you need to read or write data from the beginning of a file multiple times. It eliminates the need to close & reopen the file or manually move the file pointer using fseek().
How to Use the fseek() Function in C
The fseek() function in C is used to move the file pointer to a specific position within a file. It allows you to perform random access operations on a file by specifying the offset and the reference position.
The syntax of the fseek() function is
int fseek(FILE *stream, long int offset, int whence);
In this syntax :
- `stream` is the file pointer to the file you want to manipulate.
- `offset` is the number of bytes to move the file pointer. A positive value moves the pointer forward, while a negative value moves it backward.
- `whence` is the reference position from where the offset is applied. It can be one of the following constants:
- `SEEK_SET`: The offset is measured from the beginning of the file.
- `SEEK_CUR`: The offset is measured from the current position of the file pointer.
- `SEEK_END`: The offset is measured from the end of the file.
For example :
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
// Open the file in read mode
file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Move the file pointer to the middle of the file
fseek(file, 0, SEEK_END);
long int fileSize = ftell(file);
fseek(file, fileSize / 2, SEEK_SET);
// Read data from the middle of the file
fgets(buffer, sizeof(buffer), file);
printf("Data from the middle of the file: %s", buffer);
// Move the file pointer 10 bytes backward from the current position
fseek(file, -10, SEEK_CUR);
// Read data after moving the pointer backward
fgets(buffer, sizeof(buffer), file);
printf("Data after moving backward: %s", buffer);
// Close the file
fclose(file);
return 0;
}
- In this example, we have a file named "data.txt" that contains some text data. We open the file in read mode using fopen() with the "r" mode.
- To move the file pointer to the middle of the file, we first use fseek() with `SEEK_END` to move the pointer to the end of the file. Then, we use ftell() to get the current position, which gives us the file size. We divide the file size by 2 to calculate the middle position and use fseek() with `SEEK_SET` to move the pointer to that position.
- After moving the pointer to the middle, we use fgets() to read data from that position and print it.
- Next, we demonstrate moving the file pointer backward. We use fseek() with `SEEK_CUR` and a negative offset of -10 to move the pointer 10 bytes backward from its current position.
- After moving the pointer backward, we use fgets() to read data from the new position and print it.
- Finally, we close the file using fclose().
Note: The fseek() function provides flexibility in navigating through a file and performing random access operations. It allows you to move the file pointer to specific positions based on the offset and reference position.
Find a Specific Record in a File
To find a specific record in a file, you can use the fseek() function to move the file pointer to the desired record position & then read the record using fread().
For example :
#include <stdio.h>
typedef struct {
int id;
char name[50];
float grade;
} Student;
int main() {
FILE *file;
Student student;
int studentId, found = 0;
// Open the file in read mode
file = fopen("students.dat", "r");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Get the student ID to search for
printf("Enter the student ID to search: ");
scanf("%d", &studentId);
// Read records from the file & search for the student ID
while (fread(&student, sizeof(Student), 1, file) == 1) {
if (student.id == studentId) {
printf("Student found:\n");
printf("ID: %d\n", student.id);
printf("Name: %s\n", student.name);
printf("Grade: %.2f\n", student.grade);
found = 1;
break;
}
}
if (!found) {
printf("Student with ID %d not found.\n", studentId);
}
// Close the file
fclose(file);
return 0;
}
- In this example, we have a file named "students.dat" that contains student records. Each record consists of a student ID, name, & grade. We open the file in read mode using fopen() with the "r" mode.
- We prompt the user to enter the student ID to search for. Then, we use a loop to read records from the file one by one using fread(). Inside the loop, we compare the student ID of each record with the searched ID.
- If a match is found, we print the details of the student (ID, name, & grade) & set the `found` flag to 1 to indicate that the student record was found. We also use the `break` statement to exit the loop since we have found the desired record.
- If the loop completes without finding a match, the `found` flag remains 0, & we print a message indicating that the student was not found.
- Finally, we close the file using fclose().
File Modes for Reading and Writing Files
When opening a file using the fopen() function in C, you need to specify the mode in which you want to open the file. The mode determines the operations you can perform on the file, such as reading, writing, or appending. Let’s look at the commonly used file modes:
1. "r" (Read Mode):
- Opens a file for reading.
- The file must exist, otherwise fopen() returns NULL.
- The file pointer is positioned at the beginning of the file.
- You can only read from the file in this mode.
2. "w" (Write Mode):
- Opens a file for writing.
- If the file doesn't exist, it is created.
- If the file exists, its contents are truncated (overwritten).
- The file pointer is positioned at the beginning of the file.
- You can only write to the file in this mode.
3. "a" (Append Mode):
- Opens a file for appending.
- If the file doesn't exist, it is created.
- The file pointer is positioned at the end of the file.
- You can only write to the file in this mode, and the new data is appended to the end of the file.
4. "r+" (Read and Write Mode):
- Opens a file for both reading and writing.
- The file must exist, otherwise fopen() returns NULL.
- The file pointer is positioned at the beginning of the file.
- You can read from and write to the file in this mode.
5. "w+" (Read and Write Mode):
- Opens a file for both reading and writing.
- If the file doesn't exist, it is created.
- If the file exists, its contents are truncated (overwritten).
- The file pointer is positioned at the beginning of the file.
- You can read from and write to the file in this mode.
6. "a+" (Read and Append Mode):
- Opens a file for both reading and appending.
- If the file doesn't exist, it is created.
- The file pointer is positioned at the end of the file for writing, but you can read from anywhere in the file.
- You can read from and write to the file in this mode, and the new data is appended to the end of the file.
Let’s see an example that shows opening a file in different modes:
FILE *file;
// Open a file in read mode
file = fopen("data.txt", "r");
// Open a file in write mode
file = fopen("output.txt", "w");
// Open a file in append mode
file = fopen("log.txt", "a");
// Open a file in read and write mode
file = fopen("config.txt", "r+");
// Open a file in read and append mode
file = fopen("database.txt", "a+");
When opening a file, choose the appropriate mode based on your requirements. If you only need to read from a file, use the "r" mode. If you want to write to a file and overwrite its contents, use the "w" mode. If you want to append data to a file, use the "a" mode. If you need both reading and writing capabilities, use the "r+", "w+", or "a+" modes accordingly.
Note: Remember to always check if the file was opened successfully by checking if the returned file pointer is not NULL.
File Mode Combinations
In addition to the basic file modes mentioned earlier, you can also combine them with additional characters to specify binary mode or text mode.
Some commonly used file mode combinations are :
1. "rb" (Read Binary Mode):
- Opens a file for reading in binary mode.
- The file must exist, otherwise fopen() returns NULL.
- The file pointer is positioned at the beginning of the file.
- In binary mode, data is read & written as-is, without any translations.
2. "wb" (Write Binary Mode):
- Opens a file for writing in binary mode.
- If the file doesn't exist, it is created.
- If the file exists, its contents are truncated (overwritten).
- The file pointer is positioned at the beginning of the file.
- In binary mode, data is written as-is, without any translations.
3. "ab" (Append Binary Mode):
- Opens a file for appending in binary mode.
- If the file doesn't exist, it is created.
- The file pointer is positioned at the end of the file.
- In binary mode, data is appended to the end of the file as-is, without any translations.
4. "r+b" or "rb+" (Read and Write Binary Mode):
- Opens a file for both reading & writing in binary mode.
- The file must exist, otherwise fopen() returns NULL.
- The file pointer is positioned at the beginning of the file.
- In binary mode, data is read & written as-is, without any translations.
5. "w+b" or "wb+" (Read and Write Binary Mode):
- Opens a file for both reading & writing in binary mode.
- If the file doesn't exist, it is created.
- If the file exists, its contents are truncated (overwritten).
- The file pointer is positioned at the beginning of the file.
- In binary mode, data is read & written as-is, without any translations.
6. "a+b" or "ab+" (Read and Append Binary Mode):
- Opens a file for both reading & appending in binary mode.
- If the file doesn't exist, it is created.
- The file pointer is positioned at the end of the file for writing, but you can read from anywhere in the file.
- In binary mode, data is read & appended to the end of the file as-is, without any translations.
Let’s look at an example that shows opening a file in different mode combinations:
FILE *file;
// Open a file in read binary mode
file = fopen("data.bin", "rb");
// Open a file in write binary mode
file = fopen("output.bin", "wb");
// Open a file in append binary mode
file = fopen("log.bin", "ab");
// Open a file in read & write binary mode
file = fopen("config.bin", "r+b");
// Open a file in read & append binary mode
file = fopen("database.bin", "a+b");
Using binary mode combinations is useful when working with binary files, such as images, audio files, or custom binary formats. In binary mode, data is read & written exactly as it is stored on disk, without any text-mode translations or character conversions.
On the other hand, when working with text files, you can use the basic file modes without the "b" character, such as "r", "w", "a", "r+", "w+", or "a+". In text mode, certain character translations may occur, such as converting newline characters between different platforms.
Frequently Asked Questions
How do I open a file in both read & write mode?
To open a file in both read & write mode, use the "r+" mode in the fopen() function. This allows you to read from & write to the file.
What happens if I open an existing file in write mode ("w")?
If you open an existing file in write mode ("w"), the file's contents are truncated (deleted) & you start with an empty file.
How can I append data to the end of a file?
To append data to the end of a file, open the file in append mode ("a" or "a+"). This positions the file pointer at the end of the file, allowing you to write new data without overwriting existing content.
Conclusion
In this article, we talked about the random access files in C and covered topics like types of access methods, functions for random access, creating & writing to random access files, using rewind() & fseek(), finding specific records, & file mode combinations. These concepts help you to efficiently work with files, perform random access operations, & manipulate file contents according to your program's requirements.
You can also check out our other blogs on Code360.