'how to write a correct search function in C?
i have a problem in 'search' function, keep showing 'record not found' i have successfully save it into file and i can display it. can someone tell me in which part i wrote it wrong?
typedef struct vaccine{
char vacname[20];
char code[5];
char country[20];
int dosage, quantity;
float population;
}vaccine;
void addVaccine(){
vaccine *v;
FILE *fp;
int n, i;
printf("Enter how many vaccine you want: ");
scanf("%d",&n);
v= (vaccine*)calloc(n, sizeof(vaccine));
fp = fopen("vaccine.txt","w");
for(i=0;i<n;i++){
printf("Enter Vaccine Name: ");
scanf("%s", v[i].vacname);
printf("Enter Code: ");
scanf("%s", v[i].code);
printf("Enter Country: ");
scanf("%s", v[i].country);
printf("Enter Dosage: ");
scanf("%d", &v[i].dosage);
printf("Enter Quantity: ");
scanf("%d", &v[i].quantity);
printf("Enter Population: ");
scanf("%.2f", &v[i].population);
fwrite(&v[i],sizeof(vaccine),1,fp);
}
fclose(fp);
}
here is my search function which i have problem with;
void search(){
vaccine v;
FILE *fp;
int i, code, found=0;
fp = fopen("vaccine.txt","r");
printf("Enter code to search: ");
scanf("%s", &code);
while(fread(&v,sizeof(vaccine),1,fp))
{
if(v.code == code){
found=1;
printf("\n%s\t%s\t%d",
v.vacname,v.code,v.quantity);
}
}
if(!found)
printf("\nRecord Not Found");
fclose(fp);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
