In C, binary files can store multiple records efficiently using structures. In this program, the user enters details of multiple students, and each record is written to the binary file data.dat using the fwrite() function inside a loop.
How It Works?
fopen() in "wb" mode.for loop to accept details of multiple students.fwrite().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", "wb"); if(fp == NULL) { printf("Error opening file!"); return; } for(k = 0; k <= 2; k++) { printf("Enter the Name : "); scanf("%s", s[k].name); printf("\n Enter Roll No. : "); scanf("%d", &s[k].rollno); printf("\n Enter the Fees : "); scanf("%d", &s[k].fees); fwrite(&s[k], sizeof(s[k]), 1, fp); } fclose(fp); getch(); }
Binary File:
fwrite() function.fopen("employee.dat","wb"), use a for loop to accept details, and write each record using fwrite().
#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", "wb"); for(k = 0; k < 3; k++) { printf("Enter Employee ID : "); scanf("%d", &e[k].id); printf("\nEnter Employee Name : "); scanf("%s", e[k].name); printf("\nEnter Employee Salary : "); scanf("%d", &e[k].salary); fwrite(&e[k], sizeof(e[k]), 1, fp); } fclose(fp); getch(); }
employee.dat using the fwrite() function inside a for loop. This allows multiple records to be stored efficiently in a binary file.