7.2) Sequential and Random file access in C

Sequential File Access in C

Sequential file access involves reading or writing data in the order it appears in the file, from the beginning to the end. It’s like reading a book page by page or writing a story step by step.

Example: Sequential File Reading

Suppose you have a file named data.txt with some numbers, each on a separate line.

#include <stdio.h>

int main() {
    FILE *filePointer;
    int num;

    filePointer = fopen("data.txt", "r");

    if (filePointer == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    while (fscanf(filePointer, "%d", &num) != EOF) {
        printf("%d\n", num);
    }

    fclose(filePointer);

    return 0;
}

Random File Access in C

Random file access involves reading or writing data at any position in the file, not just sequentially. It’s like jumping to any page in a book without reading the previous pages.

Example: Random File Writing

Suppose you want to write data to a file named records.dat at specific positions.

#include <stdio.h>

struct Record {
    int id;
    float score;
};

int main() {
    FILE *filePointer;
    struct Record record;

    filePointer = fopen("records.dat", "wb");

    if (filePointer == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    record.id = 101;
    record.score = 85.5;
    fseek(filePointer, sizeof(struct Record) * 2, SEEK_SET); // Jump to the third record
    fwrite(&record, sizeof(struct Record), 1, filePointer);

    fclose(filePointer);

    return 0;
}

In this example, fseek is used to move the file pointer to the desired position, and fwrite writes the data at that position.

Output:

After running the random file access example, the file records.dat will contain data at the specified positions.

Understanding these concepts is essential for working with files in C. Sequential access is ideal when you want to process data in the order it’s stored, like reading logs. Random access is helpful when you need to access specific data without reading through the entire file, like in databases.

Leave a Reply