-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handler.c
More file actions
85 lines (78 loc) · 2.35 KB
/
file_handler.c
File metadata and controls
85 lines (78 loc) · 2.35 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
#include <stdio.h>
#include "file_handler.h"
int file_exists(const char *path) {
FILE *f = fopen(path, "rb");
if (f) { fclose(f); return 1; }
return 0;
}
void ensure_data_file() {
if (!file_exists(STUDENT_DATA_FILE)) {
FILE *f = fopen(STUDENT_DATA_FILE, "wb");
if (f) fclose(f);
}
}
int find_student_by_id(int id, Student *out, long *position) {
ensure_data_file();
FILE *fp = fopen(STUDENT_DATA_FILE, "rb");
if (!fp) return 0;
Student s;
long pos = 0;
while(fread(&s, sizeof(Student), 1, fp) == 1) {
if (s.id == id) {
if (out) *out = s;
if (position) *position = pos;
fclose(fp);
return 1;
}
pos += sizeof(Student);
}
fclose(fp);
return 0;
}
void updateStudentRoomInFile(int id) {
ensure_data_file();
FILE *fp = fopen(STUDENT_DATA_FILE, "rb+");
if (!fp) { printf("Failed to open data file\n"); return; }
Student s;
long pos = 0;
while(fread(&s, sizeof(Student), 1, fp) == 1) {
if (s.id == id) {
printf("Current Room: %d\nEnter new room: ", s.room);
if (scanf("%d", &s.room) != 1) { while(getchar()!='\n'); printf("Invalid room\n"); fclose(fp); return; }
fseek(fp, pos, SEEK_SET);
if (fwrite(&s, sizeof(Student), 1, fp) != 1) {
printf("Failed to update student record\n");
} else {
printf("Room updated successfully\n");
}
fclose(fp);
return;
}
pos += sizeof(Student);
}
printf("Student with ID %d not found\n", id);
fclose(fp);
}
void increaseMealCount(int id) {
ensure_data_file();
FILE *fp = fopen(STUDENT_DATA_FILE, "rb+");
if (!fp) { printf("Failed to open data file\n"); return; }
Student s;
long pos = 0;
while(fread(&s, sizeof(Student), 1, fp) == 1) {
if (s.id == id) {
s.mealCount += 1;
fseek(fp, pos, SEEK_SET);
if (fwrite(&s, sizeof(Student), 1, fp) != 1) {
printf("Failed to update meal count\n");
} else {
printf("Meal count increased. Total meals: %d\n", s.mealCount);
}
fclose(fp);
return;
}
pos += sizeof(Student);
}
printf("Student with ID %d not found\n", id);
fclose(fp);
}