Mình muốn viết 1 function có chức năng tìm tên ở trong 1 file text và in ra các thông tin của nhân vật mình search nhưng hiện tại mình chưa có ý tưởng viết như thế nào hay nên mong các bác gợi ý!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_LENGTH 100
struct student
{
char code[MAX_LENGTH];
char name[MAX_LENGTH];
char bdate[MAX_LENGTH];
double point;
}a;
void listing(struct student a)
{
int i;
char x;
char check;
FILE *fp;
fp = fopen("Student.txt", "a+");
if(fp == NULL)
{
printf("File doesn't exit.");
exit(0);
}
while(1)
{
printf("Enter new student:\n");
printf("Student code: ");
fgets(a.code, sizeof a.code, stdin);
setbuf(stdin, NULL);
printf("Student name: ");
fgets(a.name, sizeof a.name, stdin);
setbuf(stdin, NULL);
printf("Date of birth: ");
fgets(a.bdate, sizeof a.bdate, stdin);
setbuf(stdin, NULL);
printf("Learning point: ");
while(((scanf("%lf%c", &a.point, &x) != 2 || x != '\n') && clear_stdin()) || a.point < 0 || a.point > 10)
{
printf("Invalid input, try again!\n");
printf("Learning point: ");
}
fwrite(&a, sizeof a, 1, fp);
printf("Press enter to continue, Esc to return the main menu");
check = fgetc(stdin);
if(check == '\n')
{
continue;
}
else if(check == '1')
{
break;
}
check = getchar();
}
fclose(fp);
}
void search_name(struct student a)
{
FILE *fp;
fp = fopen("Student.txt", "r");
}
void display(struct student a)
{
int i, n;
FILE *fp;
fp = fopen("Student.txt", "r");
printf("Student list:\n");
printf("---------------------------\n");
while(fread(&a, sizeof a, 1, fp) > 0)
{
printf("Student code: %s\nStudent name: %s\nDate of birth: %s\nLearning point: %.1lf\n", a.code, a.name, a.bdate, a.point);
printf("---------------------------\n");
}
printf("\n");
fclose(fp);
}
int clear_stdin()
{
while(getchar() != '\n');
return 1;
}
int main()
{
int choice, n = 0;
char c;
FILE *fp;
while(1)
{
printf("1) Enter student list\n");
printf("2) Look up student\n");
printf("3) Display student list\n");
printf("4) Exit\n\n");
printf("Please choose menu (1->4): ");
while(((scanf("%d%c", &choice, &c) != 2 || c != '\n') && clear_stdin()) || choice > 4 || choice < 1)
{
printf("Invalid input, try again!\n\n");
printf("1) Enter student list\n");
printf("2) Look up student\n");
printf("3) Display student list\n");
printf("4) Exit\n\n");
printf("Please choose menu (1->4): ");
}
switch(choice)
{
case 1:
listing(a);
break;
case 2:
search_name(a);
break;
case 3:
display(a);
break;
case 4:
exit(0);
break;
}
}
return 0;
}