Duplicate last entry when reading a file using fread

Possible Duplicates: Why is this C code buggy? Problem with EOF when determine stream end

I'm trying to read a binary file in 4 byte chunks. However the first implementation (shown below) will duplicate the last entry and only the last entry.

FILE* f = fopen("test.a", "r+b");
char buffer[4];
while (!feof(f)) {
    fread(buffer, 4, 1, f);
    printf("read %x\n",*(int*)buffer);
}
fclose(f);

This alternative implementation does not have that issue. When should feof be used? And why is feof in the previous implementation causing the last entry to be read twice? Is there a better way to construct the buffer than casting the pointer as I have done in the printf statement? Is there anything else wrong with this code?

FILE* f = fopen("test.a", "r+b");
char buffer[4];
while (fread(buffer, 4, 1, f)) {
    printf("read %x\n",*(int*)buffer);
}
fclose(f);

Answers


This is because the eof mark is set in the file once nothing can be read from it. This causes the last fread to read "some", but not stablishing the eof mark. Then, the next loop, fread will read nothing, and then cause the eof mark to be set in the file. As fread has not changed the buffer, you have in it the last line, printed twice.


Return Value of fread:

The total number of elements successfully read is returned as a size_t object.

So you're not looking for the end of the file, you try and read again if the last read pulled anything back.


Need Your Help

reflection.proxy not valid when override

java reflection proxy-classes

It seems reflection.proxy does not what is expected when there are overriden methods. In detail, starting with simple application:

How to convert a postgres database to sqlite

database sqlite postgresql sqlite3

We're working on a website, and when we develop locally (one of us from Windows), we use sqlite3, but on the server (linux) we use postgres. We'd like to be able to import the production database ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.