what is the wrong with that loop?

106 views Asked by At

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);
}
2

There are 2 answers

0
Chand Priyankara On BEST ANSWER

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:

while(!feof(fptr))
{
    fscanf(fptr,"%d", &no);
    fscanf(fptr,"%s", &n);
    fscanf(fptr,"%s", &p);
    fscanf(fptr,"%s",&e);
    fscanf(fptr,"%s",&g);

    if(!feof(fptr)){
        printf("%6d:  ", no);
        printf("%-20s ", n);
        printf("%-15s ", p);
        printf("%-20s ", e);
        printf("%-15s \n", g);
    }
}
0
Ranger On

Change your while condition. Instead of checking for !feof(file), check if fscanf is successful(i.e., fscanf()==1). fscanf returns 1 if successful or 0 otherwise.

The last fscanf that is called reads the last line from the file and after that the while loop condition !feof(file) is checked. It will be true because the end of file is not at reached. So the loop is executed one more time.