file reading error

why is this function reading the last object of file twice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void show()
{
    ifstream f;
    f.open("BANK.PG");
    account a;
    while(1)
    {
        f.read((char*)&a,sizeof(a));
        a.show_details();
        getchar();
        if(f.eof())
        {
            cout<<"\nFile Ended";
            break;
        }
    }
}
Because f.eof() is true if the file ALREADY reached the end of file. You should loop on f.read().

1
2
3
4
5
6
while(f.read( ... ) )
{
    a.show_details();
    getchar();
    // omit f.eof()
}
Ok thank for the help.But why it is so that f.eof() is true if the file ALREADY reached the end of file.And when does eof() exactly returns false??
It returns false when it didn't reach the end of file.

Let me give you an example:

We have a 4-byte example file.

We will read 2-byte "packets".

1. Read and Store Data. read returns a nonzero value. 2/4 bytes read.
2. eof() returns false. eof flag isn't set.
3. Read and Store Data. read returns a nonzero value. 4/4 bytes read.
4. eof() returns false. eof flag isn't set.
5. Read and Store Data. read returns a zero value. Cannot go over 4/4, eof flag set.
6. eof() returns true as the eof flag is set.
awesome, I want to give a thumb up to this explanation.
Topic archived. No new replies allowed.