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?
fopen() in "rb" mode.for loop to read each record using fread().fclose().#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(); }
fread() function inside a for loop.employee.dat in "rb" mode, use fread() to read each record, and display the employee details using printf().
#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(); }
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.