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?
fopen() with "rb" mode.fread().fclose().#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(); }
fread() function.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().
#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(); }
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().