Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char search_id[100];
printf("Enter ID: ");
scanf("%s", search_id);
FILE *fp = fopen("registration.txt", "r");
if (!fp) {
perror("Cannot open input file");
exit(EXIT_FAILURE);
}
int cnt = 0;
char line[1000], id[100], name[100], gender[100], age[100], birthday[100],
food[100], start_d[100], end_d[100], course[100], fee[100];
while (fgets(line, sizeof line, fp) != NULL)
{
if (!line[strspn(line, " \t\n")]) continue; // blank or only whitespace
if (sscanf(line, " ID:%99s", id) != 1) break;
if (fscanf(fp, " Name:%99s Gender:%99s Age:%99s Birthday:%99s"
" Food:%99s Start date:%99s End date:%99s ",
name, gender, age, birthday, food, start_d, end_d) != 7) break;
// course can contain spaces
if (fgets(line, sizeof line, fp) == NULL) break;
char *p = strchr(line, ':');
if (!p) break;
strcpy(course, p + strspn(p, ": \t\n")); // skip space, copy to course
p = strchr(course, '\n'); // remove newline ...
if (p) *p = '\0'; // ... if present
if (fscanf(fp, " Fee:%99s", fee) != 1) break;
if (strcmp(id, search_id) == 0)
{
printf("\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
id, name, gender, age, birthday, food,
start_d, end_d, course, fee);
++cnt;
}
}
fclose(fp);
if (cnt == 0)
printf("\nError: id %s not found.\n", search_id);
else
printf("\nFound %d record%s for id %s.\n",
cnt, cnt > 1 ? "s" : "", search_id);
return 0;
}