why this code read the last thing in the file two times ?? can anyone help me ?? what is the problem with feof and the loop?? why it is always not correct, I tried it too many times??
thanks in advance
char n [120];
char p[120];
char e [120];
char g [120];
int no;
FILE *fptr;
fptr=fopen("answer.txt","ra+");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
printf("%6s %-20s %-15s %-15s %-15s\n","Acct#","Name","Phone","Email","Group" );
printf("------ -------------------- ------------- ------------------- --------------- \n");
currentc=firstc;
while(!feof(fptr))
{
currentc= (struct contact *) malloc(sizeof(struct contact ));
fscanf(fptr,"%d",&no);
currentc->number=no;
printf("%6d: ",currentc->number);
fscanf(fptr,"%s",&n);
strcpy(currentc->name,n);
printf("%-20s ",currentc->name);
fscanf(fptr,"%s",&p);
strcpy(currentc->phone,p);
printf("%-15s ",currentc->phone);
fscanf(fptr,"%s",&e);
strcpy(currentc->email,e);
printf("%-20s ",currentc->email);
fscanf(fptr,"%s",&g);
strcpy(currentc->group,g);
printf("%-15s ",currentc->group);
}
fclose(fptr);
}
The reason is that you are reading multiple lines in the while block, but checking feof once per multiple lines. The problem is one empty line at the end, it'll try to read another set of values. But since they are empty previous values are printing.
Simple answer will be to read once and recheck before printing: