Multiple Records Read Write


Explanation

In C, multiple records stored in a binary file can be read using the fread() function inside a loop. This program opens the binary file data.dat, reads each student record one by one, and displays the details on the screen.

How It Works?

  • Step 1: Create a structure to store student details.
  • Step 2: Declare an array of structures to hold multiple records.
  • Step 3: Open the binary file using fopen() in "rb" mode.
  • Step 4: Use a for loop to read each record using fread().
  • Step 5: Display the name, roll number, and fees of each student.
  • Step 6: 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[5];

    int k;

    FILE *fp;

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

    clrscr();

    for(k = 0; k <= 2; k++)
    {

        fread(&s[k], sizeof(s[k]), 1, fp);

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

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

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

        printf("\n\n");

    }

    fclose(fp);

    getch();

}

Output

Name : Rahul
Roll No : 101
Fees : 5000

Name : Amit
Roll No : 102
Fees : 5500

Name : Neha
Roll No : 103
Fees : 6000

Practice Exercises

Task 1: Write a C program to read and display the details of 3 employees stored in the binary file employee.dat using an array of structures.

Goal: Learn how to read multiple records from a binary file using the fread() function inside a for loop.

💡 Hint: Create an array of employee structures, open employee.dat in "rb" mode, use fread() to read each record, and display the employee details using printf().
💡 Show Solution

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

struct employee
{

    int id, salary;
    char name[20];

};

main()
{

    struct employee e[3];

    FILE *fp;

    int k;

    clrscr();

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

    if(fp == NULL)
    {

        printf("Error opening file!");

        return;

    }

    for(k = 0; k < 3; k++)
    {

        fread(&e[k], sizeof(e[k]), 1, fp);

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

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

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

        printf("\n\n");

    }

    fclose(fp);

    getch();

}

Output
Employee ID : 101
Employee Name : Amit
Employee Salary : 25000

Employee ID : 102
Employee Name : Rahul
Employee Salary : 30000

Employee ID : 103
Employee Name : Neha
Employee Salary : 28000
Explanation: The program opens employee.dat in binary read mode and reads each employee record one by one using the fread() function inside a for loop. The employee details are then displayed on the screen. This demonstrates how multiple records can be retrieved from a binary file efficiently.