-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudent.c
More file actions
98 lines (84 loc) · 2.24 KB
/
student.c
File metadata and controls
98 lines (84 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <string.h>
#include "student.h"
#include "file_handler.h"
void addStudent() {
ensure_data_file();
Student s;
FILE *fp = fopen(STUDENT_DATA_FILE, "ab");
if (!fp) {
printf("Failed to open data file for writing\n");
return;
}
printf("Enter ID (number): ");
if (scanf("%d", &s.id) != 1) {
while (getchar() != '\n');
printf("Invalid ID\n");
fclose(fp);
return;
}
// Check duplicate
Student tmp;
long pos;
if (find_student_by_id(s.id, &tmp, &pos)) {
printf("Student with ID %d already exists\n", s.id);
fclose(fp);
return;
}
printf("Enter Name: ");
getchar();
fgets(s.name, sizeof(s.name), stdin);
s.name[strcspn(s.name, "\n")] = '\0';
printf("Enter Room No: ");
if (scanf("%d", &s.room) != 1) {
while (getchar() != '\n');
printf("Invalid room\n");
fclose(fp);
return;
}
s.mealCount = 0;
s.bill = 0.0f;
if (fwrite(&s, sizeof(Student), 1, fp) != 1) {
printf("Failed to write student to file\n");
} else {
printf("Student added successfully\n");
}
fclose(fp);
}
void viewStudents() {
ensure_data_file();
FILE *fp = fopen(STUDENT_DATA_FILE, "rb");
if (!fp) {
printf("Failed to open data file for reading\n");
return;
}
Student s;
printf("\n--- All Students ---\n");
while (fread(&s, sizeof(Student), 1, fp) == 1) {
printf("ID: %d | Name: %s | Room: %d | Meals: %d | Bill: %.2f\n",
s.id, s.name, s.room, s.mealCount, s.bill);
}
fclose(fp);
}
void updateRoom() {
int id;
printf("Enter Student ID to update room: ");
if (scanf("%d", &id) != 1) {
while (getchar() != '\n');
printf("Invalid ID\n");
return;
}
updateStudentRoomInFile(id);
}
void showStudentInfo(int id) {
ensure_data_file();
Student s;
long pos;
if (find_student_by_id(id, &s, &pos)) {
printf("\n--- Student Profile ---\n");
printf("ID: %d\nName: %s\nRoom: %d\nMeals: %d\nBill: %.2f\n",
s.id, s.name, s.room, s.mealCount, s.bill);
} else {
printf("Student with ID %d not found\n", id);
}
}