Problem Solving using C Language

0 of 77 lessons complete (0%)

File Handling

Writing and Reading a Binary File

Binary files are files that store data in binary format, such as images, videos, or compiled code.

#include <stdio.h>

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

int main() {
    struct Student s1 = {"Alice", 20, 3.75};
    struct Student s2;

    // Write the binary file
    FILE *filePtr = fopen("student.dat", "wb");
    if (filePtr == NULL) {
        printf("Error! Could not open file.\n");
        return 1;
    }
    fwrite(&s1, sizeof(struct Student), 1, filePtr);
    fclose(filePtr);

    // Read the binary file
    filePtr = fopen("student.dat", "rb");
    if (filePtr == NULL) {
        printf("Error! Could not open file.\n");
        return 1;
    }
    fread(&s2, sizeof(struct Student), 1, filePtr);
    fclose(filePtr);

    printf("Name: %s\nAge: %d\nGPA: %.2f\n", s2.name, s2.age, s2.gpa);

    return 0;
}

Explanation:

  • fwrite(&s1, sizeof(struct Student), 1, filePtr): Writes the structure s1 to the binary file student.dat.
  • fread(&s2, sizeof(struct Student), 1, filePtr): Reads the data from the binary file back into the structure s2.