Read From Binary File


Explanation

In C, we can read stored data from a binary file using the fread() function. In this program, the binary file data.dat is opened in read mode and the stored student details are retrieved and displayed on the screen.

How It Works?

  • Step 1: Create the same structure that was used while writing the binary file.
  • Step 2: Open the binary file using fopen() with "rb" mode.
  • Step 3: Read the structure data from the file using fread().
  • Step 4: Display the student details stored in the file.
  • Step 5: Close the file using fclose().

Example Program


#include <stdio.h>
#include <conio.h>

struct student
{

    char name[20];
    int rollno, fees;

};

main()
{

    struct student s;

    FILE *fp;

    fp = fopen("data.dat", "rb");

    if(fp == NULL)
    {

        printf("Error opening file!");

        return;

    }

    fread(&s, sizeof(s), 1, fp);

    printf("Name : %s", s.name);

    printf("\n Roll No : %d", s.rollno);

    printf("\n Fees : %d", s.fees);

    fclose(fp);

    getch();

}

Output

Name : Rahul
Roll No : 101
Fees : 5000

Practice Exercises

Task 1: Write a C program to read employee details from a binary file named employee.dat and display the stored information on the screen.

Goal: Learn how to read structure data from a binary file using the fread() function.

💡 Hint: Create the same employee structure that was used while writing the file. Open employee.dat in "rb" mode, use fread() to read the record, and display the employee details using printf().
💡 Show Solution

#include <stdio.h>
#include <conio.h>

struct employee
{

    int id;
    char name[20];
    int salary;

};

main()
{

    struct employee e;

    FILE *fp;

    clrscr();

    fp = fopen("employee.dat", "rb");

    if(fp == NULL)
    {

        printf("Error opening file!");

        return;

    }

    fread(&e, sizeof(e), 1, fp);

    printf("Employee ID : %d", e.id);

    printf("\nEmployee Name : %s", e.name);

    printf("\nEmployee Salary : %d", e.salary);

    fclose(fp);

    getch();

}

Output
Employee ID : 101
Employee Name : Amit
Employee Salary : 25000
Explanation: The program opens employee.dat in binary read mode using fopen(). It reads one employee record using fread() and displays the employee ID, name, and salary on the screen. Finally, the file is closed using fclose().