How to validate the User Input based on the Student Number.
Scenario:
When the user adds the Student with the number 2015. The program will not accept another student id number 2015.
void add_student(){
int isFound = 0;
FILE *fp; // to open a file, fopen, fclose.
fp = fopen("record.txt","ab+"); //fopen() function creates the file if it does not exist. --ab+ Open a binary file in append mode for writing at the end of the file.
fflush(stdin);
printf("\nStudent Name: ");gets(students.name);
printf("\nStudent ID Number: ");scanf("%s",students.ID);
printf("\nCourse: ");scanf("%s",students.course);
printf("\nYear Level: ");scanf("%d",&students.yrlvl);
printf("\nAge: ");scanf("%d",&students.age);
FILE *fa;
fa = fopen("record.txt","r");
while(fread(&students,sizeof(students),1,fa) == 1) //
{
if(strcmp(students.ID,students.ID) == 0) // Check if the user already in the file
{
isFound = 1;
break;
}
}
if(isFound == 1)
{
printf("\nStudent ID Number: %s already in the System. Please select Edit to modify same Student ID", students.ID);
}
else
{
fwrite(&students, sizeof(students), 1, fp); // Add Student
printf("\nAdded Successfully");
}
fclose(fa);
fclose(fp);// close the file
return;
}
This is the all data from the file. enter image description here
When I add another student with the number 2016 this is the error