C Lesson 35 – File Handling Project | Dataplexa

File Handling Mini Project

In the previous lessons, you learned:

  • Opening and closing files
  • Text file operations
  • Formatted file I/O
  • Binary file handling

Now it is time to combine everything into a small but meaningful project.


Project Overview

We will build a Student Record Management Program using binary files.

The program will:

  • Store student records in a file
  • Read records from the file
  • Display stored data

Data Design

Each student will have:

  • Roll number
  • Name
  • Marks

We will store this data using a structure.


Program Code


#include <stdio.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

int main() {
    FILE *fp;
    struct Student s;

    fp = fopen("students.dat", "wb");

    printf("Enter roll number: ");
    scanf("%d", &s.roll);

    printf("Enter name: ");
    scanf("%s", s.name);

    printf("Enter marks: ");
    scanf("%f", &s.marks);

    fwrite(&s, sizeof(s), 1, fp);
    fclose(fp);

    printf("\nRecord saved successfully.\n");

    fp = fopen("students.dat", "rb");
    fread(&s, sizeof(s), 1, fp);

    printf("\n--- Student Details ---\n");
    printf("Roll: %d\n", s.roll);
    printf("Name: %s\n", s.name);
    printf("Marks: %.2f\n", s.marks);

    fclose(fp);
    return 0;
}

How This Program Works

Let’s break it down step by step:

  • A structure holds student data
  • The file is opened in binary write mode
  • Data is written using fwrite()
  • The file is reopened in read mode
  • Data is read using fread()

Why Binary Files Here?

Binary files allow:

  • Fast read and write operations
  • Exact storage of structures
  • Efficient memory usage

This approach is used in real applications and systems.


Mini Practice

  • Modify the program to store multiple students
  • Add a loop to accept more records
  • Display all student records

Quick Quiz

Q1. Which function writes structures to a binary file?

fwrite()

Q2. Which function reads structures from a binary file?

fread()

Q3. Why use binary files for records?

They are fast and store exact memory data.

Q4. Can structures be stored directly in binary files?

Yes.

Q5. Is this approach used in real applications?

Yes.