C Crud
C Crud
h>
#include <stdlib.h>
#include <string.h>
// Function prototypes
void addStudent();
void viewStudents();
void updateStudent();
void deleteStudent();
void saveToFile(Student students[], int count);
void loadFromFile(Student students[], int *count);
int main() {
int choice;
Student students[MAX];
int count = 0;
loadFromFile(students, &count);
while (1) {
printf("\n=== Student Management System ===\n");
printf("1. Add Student\n");
printf("2. View All Students\n");
printf("3. Update Student\n");
printf("4. Delete Student\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addStudent();
break;
case 2:
viewStudents();
break;
case 3:
updateStudent();
break;
case 4:
deleteStudent();
break;
case 5:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}
void addStudent() {
FILE *fp = fopen("student_data.txt", "a");
if (!fp) {
printf("Error opening file!\n");
return;
}
Student s;
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter Course: ");
scanf("%s", s.course);
printf("Enter Date (e.g., YYYY-MM-DD): ");
scanf("%s", s.date);
printf("Enter Address: ");
scanf("%s", s.address);
printf("Enter Phone Number: ");
scanf("%s", s.phone);
void viewStudents() {
FILE *fp = fopen("student_data.txt", "r");
if (!fp) {
printf("No data found.\n");
return;
}
Student s;
printf("\n=== Student List ===\n");
while (fscanf(fp, "%s %s %s %s %s", s.name, s.course, s.date, s.address,
s.phone) != EOF) {
printf("Name: %s\n", s.name);
printf("Course: %s\n", s.course);
printf("Date: %s\n", s.date);
printf("Address: %s\n", s.address);
printf("Phone: %s\n", s.phone);
printf("--------------------\n");
}
fclose(fp);
}
void updateStudent() {
FILE *fp = fopen("student_data.txt", "r");
FILE *temp = fopen("temp.txt", "w");
if (!fp || !temp) {
printf("Error opening files.\n");
return;
}
char name[100];
printf("Enter the name of the student to update: ");
scanf("%s", name);
Student s;
int found = 0;
fclose(fp);
fclose(temp);
remove("student_data.txt");
rename("temp.txt", "student_data.txt");
if (found)
printf("Student updated successfully.\n");
else
printf("Student not found.\n");
}
void deleteStudent() {
FILE *fp = fopen("student_data.txt", "r");
FILE *temp = fopen("temp.txt", "w");
if (!fp || !temp) {
printf("Error opening files.\n");
return;
}
char name[100];
printf("Enter the name of the student to delete: ");
scanf("%s", name);
Student s;
int found = 0;
fclose(fp);
fclose(temp);
remove("student_data.txt");
rename("temp.txt", "student_data.txt");
if (found)
printf("Student deleted successfully.\n");
else
printf("Student not found.\n");
}
*count = 0;
while (fscanf(fp, "%s %s %s %s %s", students[*count].name,
students[*count].course,
students[*count].date, students[*count].address,
students[*count].phone) != EOF) {
(*count)++;
}
fclose(fp);
}