there is always problem on how to use feof(), so please avoid using it...
why not to use feof() for loop exit condition. please here is link.
here is link to a good tutorial, i have combined it with your code and it works like charm...please look into it.
Below is the modified code,
struct info
{
char name[40];
char sur[40];
};
int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[40];
if((fp = fopen(fname, "r")) == NULL) {
return(-1);
}
while(fgets(temp, 40, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
int main()
{
struct info rec;
FILE *f1; //*f2;
int sel;// ser, res;
char cmp[40];
char fname[10] = "lis.txt";
int err = -1;
// int cont=0;
do{
do{
printf("1> Add account\n");
printf("2> Search account\n");
printf("3> Modify account\n");
printf("4> Exit\n");
printf("Type your choice -> ");
scanf("%d", &sel);
if(sel<1 || sel>4){
printf("ERROR: The choice isn't allowed\n");
}
}while(sel<1 || sel>4);
getchar();
switch(sel){
case 1:
f1=fopen(fname ,"a+");
if (!f1)
{
printf("lis.txt, no such file exits\n");
return -1;
}
printf("Insert new account\n");
printf("Write name: ");
fgets(rec.name, sizeof(rec.name), stdin);
printf("Write surname: ");
fgets(rec.sur, sizeof(rec.sur), stdin);
fprintf(f1,"%s",rec.name);
fprintf(f1,"%s\n",rec.sur);
fflush(f1);
printf("Account added!\n");
fclose(f1);
break;
case 2:
printf("Search account\n");
printf("Write surname to search: ");
fgets(cmp, 40, stdin);
err = Search_in_File(fname, cmp);
if(err < 0)
{
return err;
}
break;
case 3:
printf("Modify account\n");
break;
case 4:
printf("Closing...\n");
break;
default:
printf("ERROR!\n");
break;
}
}while(sel!=4);
return 0;
}