C Basics ▶
1. Introduction to C
2. History & Features
3. Installation & Setup
4. Structure of C Program
5. Data Types
6. Variables
7. Constants
8. Operators
9. Input & Output
10. Control Statements
11. Loops
12. Break & Continue
13. Arrays
14. Strings
15. Functions
Pointers & Memory ▶
16. Pointers Basics
17. Pointer Arithmetic
18. Arrays & Pointers
19. Pointers to Functions
20. Dynamic Memory Allocation
21. malloc & calloc
22. realloc & free
23. Memory Leaks
24. 2D Arrays & Pointers
25. Pointer Mini Project
Structures, Unions & Files ▶
26. Structures
27. Nested Structures
28. Unions
29. Enums
30. typedef
31. File Handling Basics
32. File Operations
33. Reading & Writing Files
34. Binary Files
35. File Handling Project
Data Structures & Algorithms ▶
36. Introduction to DSA
37. Linked Lists
38. Stacks
39. Queues
40. Trees
41. Binary Search Tree
42. Sorting Algorithms
43. Searching Algorithms
44. Graph Basics
45. DSA Mini Project
Advanced C & Projects ▶
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.