Binary File Write and Read

#include <stdio.h>

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

int main() {
    // Binary file write and read
    FILE *binaryFile;
    struct Student student;

    // Writing to a binary file
    binaryFile = fopen("students.dat", "wb");
    if (binaryFile != NULL) {
        strcpy(student.name, "John Doe");
        student.age = 20;
        student.gpa = 3.75;

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

        fclose(binaryFile);
        printf("Student data written to the binary file.\n");
    } else {
        printf("Unable to open the binary file.\n");
    }

    // Reading from a binary file
    binaryFile = fopen("students.dat", "rb");
    if (binaryFile != NULL) {
        fread(&student, sizeof(struct Student), 1, binaryFile);

        fclose(binaryFile);
        printf("Student Data:\nName: %s\nAge: %d\nGPA: %.2f\n", student.name, student.age, student.gpa);
    } else {
        printf("Unable to open the binary file.\n");
    }

    return 0;
}
chevron_left
chevron_right

Leave a comment

Your email address will not be published. Required fields are marked *

Comment
Name
Email
Website