Write To Binary File


Explanation

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?

  • Step 1: Create a structure to store student details.
  • Step 2: Declare a file pointer using FILE *fp.
  • Step 3: Open the binary file using fopen() with "wb" mode.
  • Step 4: Accept student information using scanf().
  • Step 5: Write structure data into the file using fwrite().
  • 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;

    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();

}

Output

Enter the Name : Rahul
Enter Roll No. : 101
Enter the Fees : 5000


Binary File:

data.dat file created successfully.

Practice Exercises

Task 1: Write a C program to create a binary file named employee.dat and store employee details using a structure.

Accept the following details:
  • Employee ID
  • Employee Name
  • Employee Salary
Goal: Learn how to store structure data into a binary file using the fwrite() function.

💡 Hint: Create a structure for employee details, open the file using fopen("employee.dat","wb"), accept data using scanf(), and write the structure into the file using fwrite().
💡 Show Solution

#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();

}

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


employee.dat file created successfully.
Explanation: The program creates a structure to store employee information. The entered employee details are stored in a binary file using the fwrite() function. Binary files store data in byte format, which makes data storage faster and more efficient.