Sequential and Random Access File Operations

In the world of programming, file operations play a crucial role in storing and retrieving data. When it comes to C programming, working with files is no different. Two common methods of file access are sequential and random access. In this article, we will explore both these approaches and discuss their differences, advantages, and usage scenarios.

Sequential File Access

Sequential file access refers to reading or writing data in a sequential manner, starting from the beginning of the file and continuing till the end. In a sequential file, records are stored one after another without any gaps. This means that to access a particular record, we need to traverse through all the preceding records.

Reading Sequentially

To read a sequential file, we use the fscanf function or its variant fgets to read individual lines or fields from the file. We can read data until the end of the file is reached using a loop that reads one record at a time. This method is efficient when we need to process data in a specific order, such as analyzing a log file or processing a set of sequential instructions.

Here's an example of reading a sequential file in C:

#include <stdio.h>

int main() {
    FILE *file = fopen("sample.txt", "r");
    if (file == NULL) {
        printf("Failed to open the file.");
        return 1;
    }

    char line[100];
    while (fgets(line, sizeof(line), file) != NULL) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}

Writing Sequentially

To write to a sequential file, we use the fprintf function to write data to the file one record at a time. Similar to reading, we can perform this operation within a loop. Sequential file writing is commonly used when we want to generate reports or log data in a systematic manner.

Here's an example of writing to a sequential file in C:

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Failed to create the file.");
        return 1;
    }

    for (int i = 1; i <= 10; i++) {
        fprintf(file, "Record %d\n", i);
    }

    fclose(file);
    return 0;
}

Random Access File Access

Unlike sequential access, random access allows direct access to any record in a file. In other words, we can read or write to any record without traversing through the preceding records. Random access files are typically used when we need to directly access specific data or modify existing records at any given position.

Reading Randomly

To read from a random access file, we use the fread function to read a specific number of bytes from the desired position in the file. We first need to position the file pointer to the appropriate record using the fseek function. Random access reading is useful when working with large files or when the order of data retrieval is not essential.

Here's an example of reading from a random access file in C:

#include <stdio.h>

struct Book {
    char title[50];
    char author[50];
    int year;
};

int main() {
    FILE *file = fopen("books.dat", "rb");
    if (file == NULL) {
        printf("Failed to open the file.");
        return 1;
    }

    struct Book book;
    int recordNumber = 3;

    fseek(file, (recordNumber - 1) * sizeof(struct Book), SEEK_SET);
    fread(&book, sizeof(struct Book), 1, file);

    printf("Title: %s\n", book.title);
    printf("Author: %s\n", book.author);
    printf("Year: %d\n", book.year);

    fclose(file);
    return 0;
}

Writing Randomly

To write to a random access file, we use the fwrite function to write a specific number of bytes to the desired position in the file. Similar to random access reading, we need to position the file pointer using the fseek function before writing the data. Random access writing is effective when we want to update or delete specific records in a file without rewriting the entire file.

Here's an example of writing to a random access file in C:

#include <stdio.h>

struct Student {
    char name[50];
    int age;
};

int main() {
    FILE *file = fopen("students.dat", "rb+");
    if (file == NULL) {
        printf("Failed to open the file.");
        return 1;
    }

    struct Student student;
    int recordNumber = 2;

    fseek(file, (recordNumber - 1) * sizeof(struct Student), SEEK_SET);

    printf("Enter the student name: ");
    scanf("%s", student.name);
    printf("Enter the student age: ");
    scanf("%d", &student.age);

    fwrite(&student, sizeof(struct Student), 1, file);

    fclose(file);
    return 0;
}

Conclusion

Sequential and random access file operations offer different ways to work with files in C programming. Sequential access is suitable when data needs to be read or written in a specific order, while random access allows direct access to any record. Choosing the appropriate method depends on the specific requirements of your program. Understanding these concepts is crucial for efficient file handling in C, enabling developers to create more robust and versatile applications.


noob to master © copyleft