7.4) Binary Files in C

Binary files store data in its raw binary format, without any special formatting or encoding. This makes binary files more efficient for storing complex data structures, images, audio, and other non-textual data.

Unlike text files, which store data as human-readable characters, binary files store data as a sequence of bytes.

Writing and Reading Binary Files

Suppose you want to store and retrieve information about students using a binary file.

#include <stdio.h>

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

int main() {
    FILE *filePointer;
    struct Student student;

    // Writing to a binary file
    filePointer = fopen("students.dat", "wb");

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

    student.rollNumber = 101;
    strcpy(student.name, "Alice");
    fwrite(&student, sizeof(struct Student), 1, filePointer);

    fclose(filePointer);

    // Reading from the binary file
    filePointer = fopen("students.dat", "rb");

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

    fread(&student, sizeof(struct Student), 1, filePointer);
    printf("Roll Number: %d\nName: %s\n", student.rollNumber, student.name);

    fclose(filePointer);

    return 0;
}

Output:

Roll Number: 101
Name: Alice

In this example, the program creates a binary file named students.dat and writes a student’s data to it. Then, it reads the data back from the file and prints it.

Benefits of Binary Files

  • Efficiency: Binary files use less space to store the same data compared to text files.
  • Complex Data: Binary files can store complex data structures like structs and arrays directly, without any additional formatting.

Considerations

  • Portability: Be cautious when sharing binary files between different systems due to endianness and data alignment differences.

When working with binary files, you have more control over the data you store, making them suitable for various applications where data integrity and efficiency are crucial.

Leave a Reply