Student database in C (file handling)
Add, search, update and delete student records saved in a binary file, the classic C mini project done properly.
What you'll learn
- âstructs and arrays of structs
- âfread/fwrite and fseek for random access
- âSafe input with fgets
What you'll build
- âAdd, list, search by roll number
- âUpdate and delete records
- âSort by marks
- âData survives restarts
Step-by-step guide
- 1
Define the record
typedef struct { int roll; char name[50]; float marks; } Student; with a fixed size so records can be found by position.
- 2
Add a record
Open "students.dat" with "ab", fwrite(&s, sizeof(Student), 1, fp). Read the name with fgets and strip the newline (never use gets).
- 3
List and search
Open with "rb" and fread one record at a time until it returns 0; compare roll numbers.
- 4
Update in place
Open with "rb+", find the record, fseek(fp, -(long)sizeof(Student), SEEK_CUR) and fwrite the new data.
- 5
Delete
Copy every record except the deleted one into temp.dat, then remove() the old file and rename() temp.dat.
- 6
Sort
Load all records into a malloc'd array, qsort with a comparator on marks, print, then free().
- 7
Menu and checks
A do-while menu; check every fopen for NULL and every scanf return value.
đ Make it stand out
- +Index file for faster search
- +Password-protected admin menu
- +Export to CSV