Problem with EOF

Hi!

I want read my file by this:
1
2
3
4
5
6
7
while(!feof(f)){
fread(&buf, sizeof(buf), 1, f);
value = buf.id;
...............
}

//buf is struct 


Problem is always with the last one struct/record from file.
I get twice the same record - always the last

Anybody can help??

PS. File is saved good. Last is only one writed.
Last edited on
my guess:

the reading of the last line:
1. check if eof (ok)
2. read a line (the last one). fread only reads the bytes that are there and therefore doesn't reach eof.
3. you do something with buf.
4. check if eof (still ok)
5. read a line (which doesn't exist, so you reach eof. no bytes are read, so buf remains the same)
6. you do something with buf (which is teh same)
7. check if eof (not ok)

the solution would be
1
2
3
4
5
while(true){
    fread(...);
    if(feof(f)) break;
    ...
}

that's c.
in c++ it could be slightly prettier:
1
2
3
while(file.read(...)){
    ...
}
Last edited on
Thanks, it works!
You want to be careful with the fread() and feof() response. Just like in C++ streams, the read operation may hit the end of file but still return valid data.

A better option is to work off of the return value for fread(), and check afterwards to make sure you hit EOF and not some other error:

1
2
3
4
5
6
7
8
while (fread(..., f) != 0)
{
    ...
}
if (!feof(f))
{
    fooey();
}

In C++ it would be the same:

1
2
3
4
5
6
7
8
while (f.read(...))
{
    ...
}
if (!f.eof())
{
    fooey();
}

Hope this helps.
Topic archived. No new replies allowed.