HW1code.c
2.27 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
#define MAX_RESIDENTS 100
#define MAX_LENGTH 100
// Define the structures
typedef struct {
char student_code[MAX_LENGTH];
char name[MAX_LENGTH];
char id_code[MAX_LENGTH];
} Student;
typedef struct {
char id_code[MAX_LENGTH];
char city[MAX_LENGTH];
} Resident;
// Function to read students from F1.txt
int read_students(const char *file_name, Student students[]) {
FILE *file = fopen(file_name, "r");
if (file == NULL) {
perror("Error opening file");
return -1;
}
int count = 0;
while (fscanf(file, "%[^,],%[^,],%s\n", students[count].student_code, students[count].name, students[count].id_code) != EOF) {
count++;
}
fclose(file);
return count;
}
// Function to read residents from F2.txt
int read_residents(const char *file_name, Resident residents[]) {
FILE *file = fopen(file_name, "r");
if (file == NULL) {
perror("Error opening file");
return -1;
}
int count = 0;
while (fscanf(file, "%[^,],%s\n", residents[count].id_code, residents[count].city) != EOF) {
count++;
}
fclose(file);
return count;
}
// Main function
int main() {
Student students[MAX_STUDENTS];
Resident residents[MAX_RESIDENTS];
int student_count = read_students("F1.txt", students);
int resident_count = read_residents("F2.txt", residents);
if (student_count == -1 || resident_count == -1) {
return 1;
}
char residence[MAX_LENGTH];
printf("Enter the residence: ");
scanf("%s", residence);
// Find matching students
int found = 0;
for (int i = 0; i < student_count; i++) {
for (int j = 0; j < resident_count; j++) {
if (strcmp(students[i].id_code, residents[j].id_code) == 0 && strcmp(residents[j].city, residence) == 0) {
if (!found) {
printf("Students with residence %s:\n", residence);
found = 1;
}
printf("Student Code: %s, Name: %s, ID Code: %s\n", students[i].student_code, students[i].name, students[i].id_code);
}
}
}
if (!found) {
printf("No students found with the given residence.\n");
}
return 0;
}