In C, a binary file stores data in the form of bytes instead of normal text. The fwrite() function is used to write structure data into a binary file. In this program, student details are accepted from the user and stored inside a file named data.dat.
How It Works?
FILE *fp.fopen() with "wb" mode.scanf().fwrite().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", "wb"); if(fp == NULL) { printf("Error opening file!"); return; } printf("Enter the Name : "); scanf("%s", s.name); printf("\n Enter Roll No. : "); scanf("%d", &s.rollno); printf("\n Enter the Fees : "); scanf("%d", &s.fees); fwrite(&s, sizeof(s), 1, fp); fclose(fp); getch(); }
Binary File:
fwrite() function.fopen("employee.dat","wb"), accept data using scanf(), and write the structure into the file using fwrite().
#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", "wb"); printf("Enter Employee ID : "); scanf("%d", &e.id); printf("\n Enter Employee Name : "); scanf("%s", e.name); printf("\n Enter Employee Salary : "); scanf("%d", &e.salary); fwrite(&e, sizeof(e), 1, fp); fclose(fp); getch(); }
fwrite() function. Binary files store data in byte format, which makes data storage faster and more efficient.