#include <stdio.h>
#include <stdlib.h>
struct Student {
int id;
char name[30];
int age;
};
int main() {
FILE *fp;
struct Student s;
int choice, id, found;
fp = fopen("students.dat", "ab+");
if (fp == NULL) { printf("Error opening file!"); return 1; }
while (1) {
printf("\n--- MENU ---\n");
printf("1. Add Record\n2. Display All\n3. Search by ID\n4. Update Record\n5. Exit\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
fseek(fp, 0, SEEK_END);
printf("Enter ID, Name, Age: ");
scanf("%d %s %d", &s.id, s.name, &s.age);
fwrite(&s, sizeof(s), 1, fp);
printf("Record added!\n");
break;
case 2:
rewind(fp);
printf("\nAll Records:\n");
while (fread(&s, sizeof(s), 1, fp) == 1)
printf("ID: %d Name: %s Age: %d\n", s.id, s.name, s.age);
break;
case 3:
printf("Enter ID to search: ");
scanf("%d", &id);
rewind(fp);
found = 0;
while (fread(&s, sizeof(s), 1, fp) == 1) {
if (s.id == id) {
printf("Found: %s, Age: %d\n", s.name, s.age);
found = 1;
break;
}
}
if (!found) printf("Record not found.\n");
break;
case 4:
printf("Enter ID to update: ");
scanf("%d", &id);
rewind(fp);
found = 0;
while (fread(&s, sizeof(s), 1, fp) == 1) {
if (s.id == id) {
printf("Enter new Name and Age: ");
scanf("%s %d", s.name, &s.age);
fseek(fp, -(long)sizeof(s), SEEK_CUR);
fwrite(&s, sizeof(s), 1, fp);
printf("Record updated!\n");
found = 1;
break;
}
}
if (!found) printf("Record not found.\n");
break;
case 5:
fclose(fp);
printf("Exiting...\n");
exit(0);
}
}
return 0;
}