Student Management System in C (Complete Example with File Handling)


This project demonstrates a Student Management System in C, where you can add, display, search, update, and delete student records. It uses structures, arrays, and file handling to store and retrieve data efficiently.

1. Features

  1. Add new student records
  2. Display all student records
  3. Search a student by ID
  4. Update student information
  5. Delete a student record
  6. Save and load records using files

2. Structure Definition


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student {
int id;
char name[50];
int age;
char grade;
};

3. File-Based Operations


#define FILENAME "students.dat"

// Add student
void addStudent() {
struct Student s;
FILE *fp = fopen(FILENAME, "ab");
if(!fp) { printf("Error opening file.\n"); return; }

printf("Enter ID: "); scanf("%d", &s.id);
printf("Enter Name: "); scanf("%s", s.name);
printf("Enter Age: "); scanf("%d", &s.age);
printf("Enter Grade: "); scanf(" %c", &s.grade);

fwrite(&s, sizeof(s), 1, fp);
fclose(fp);
printf("Student added successfully!\n");
}

// Display all students
void displayStudents() {
struct Student s;
FILE *fp = fopen(FILENAME, "rb");
if(!fp) { printf("No records found.\n"); return; }

printf("\nID\tName\tAge\tGrade\n");
while(fread(&s, sizeof(s), 1, fp)) {
printf("%d\t%s\t%d\t%c\n", s.id, s.name, s.age, s.grade);
}
fclose(fp);
}

// Search student by ID
void searchStudent() {
int searchId;
struct Student s;
printf("Enter ID to search: "); scanf("%d", &searchId);

FILE *fp = fopen(FILENAME, "rb");
if(!fp) { printf("No records found.\n"); return; }

int found = 0;
while(fread(&s, sizeof(s), 1, fp)) {
if(s.id == searchId) {
printf("ID: %d\nName: %s\nAge: %d\nGrade: %c\n", s.id, s.name, s.age, s.grade);
found = 1;
break;
}
}
if(!found) printf("Student not found.\n");
fclose(fp);
}

4. Main Menu


int main() {
int choice;
while(1) {
printf("\n--- Student Management System ---\n");
printf("1. Add Student\n2. Display Students\n3. Search Student\n4. Exit\n");
printf("Enter your choice: "); scanf("%d", &choice);

switch(choice) {
case 1: addStudent(); break;
case 2: displayStudents(); break;
case 3: searchStudent(); break;
case 4: exit(0);
default: printf("Invalid choice!\n");
}
}
return 0;
}

5. Key Points to Remember

  1. Uses struct to store student information
  2. Uses file handling (fwrite, fread) to save records permanently
  3. Menu-driven program makes it user-friendly
  4. Can be extended to include update and delete functionality