2

There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?

void main()
{
    struct student
    {
        char name[30], rollno[6];
    }stud;
    FILE *fp = fopen(“somefile.dat”,”r”);
    while(!feof(fp))
    {
        fread(&stud, sizeof(stud), 1 , fp);
        puts(stud.name);
    }
}
bosnjak
  • 8,424
  • 2
  • 21
  • 47
Andrei Vieru
  • 154
  • 1
  • 11

4 Answers4

4

The feof function causes the loop to enter once more then expected. For a full explanation, read here:
Why is “while ( !feof (file) )” always wrong?

Community
  • 1
  • 1
bosnjak
  • 8,424
  • 2
  • 21
  • 47
0

feof() only returns true if you tried to read at or past the end of the file.

When you have read the last data, you are still in the valid area of the file.

When the condition is checked in the next iteration, it's still the same. Sou you will read again, this time after the end of the file. So you read zero characters, enter that "nothing" into your string (so it remains unchanged), and print it again. Only after that (because you passed the end of the file), will feof() return true.

vsz
  • 4,811
  • 7
  • 41
  • 78
0

This will work:

void main()
{
    struct student
    {
        char name[30], rollno[6];
    }stud;
    FILE *fp = fopen(“somefile.dat”,”r”);
    while(!feof(fp))
    {
        fread(&stud, sizeof(stud), 1 , fp);
        puts(stud.name);
        if ( feof(fp) )
           break;
    }
}
Mohammad Ashfaq
  • 1,333
  • 2
  • 14
  • 38
0

The purpose of feof() is NOT the check if the next read will reach the end of file. The purpose of feof() is distinguish between a read error and having reached the end of the file. If fread() returns 0, you call feof/ferror to take some action.

That being said, you should replace this:

    FILE *fp = fopen(“somefile.dat”,”r”);
    while(!feof(fp))
    {
        fread(&stud, sizeof(stud), 1 , fp);
        puts(stud.name);
    }

With this:

    FILE *fp = fopen(“somefile.dat”,”r”);
    fread(&stud, sizeof(stud), 1 , fp);
    while(!feof(fp))
    {            
        puts(stud.name);
        fread(&stud, sizeof(stud), 1 , fp);
    }
Pandrei
  • 4,843
  • 3
  • 27
  • 44