Andrei Vieru
Andrei Vieru

Reputation: 174

records stored in a file

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

Upvotes: 2

Views: 71

Answers (4)

bosnjak
bosnjak

Reputation: 8624

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?

Upvotes: 3

Pandrei
Pandrei

Reputation: 4961

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

Upvotes: 0

Mohammad Ashfaq
Mohammad Ashfaq

Reputation: 1375

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

Upvotes: 0

vsz
vsz

Reputation: 4893

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.

Upvotes: 0

Related Questions