Ex17: fread returns 0 at line 44

Hello, everyone!

I am stuck on exercise 17, any advice would be appreciated! :slight_smile:

I have spent some time now doing exercise 17 and trying to figure out why
it’s giving me “ERROR: failed to load database.”.

So the test for this output is (rc != 1), and right after line 44
(which is our rc = fread(conn->db, sizeof(struct Database), 1, conn->file)
in the code I created a new line to print out the value of rc,
which turns out to be 0.

I looked up about the read function, and found out that the return
value of fread should be equal to the third argument for fread,
which in our case we have set to 1. If they are not
equal, then either an error has occurred or the End Of File was reached.

Now I add some lines right after out int rc = fread… line, testing like so:
if (feof(conn->file)) { print stuff about EOF} else if (ferror(conn->file))
{ print stuff about some other error }. I am not sure that that would even be
a good way of testing the problem, since I am doing it after the fread
operation, which might changed the file anyways. :thinking: maybe it’s
completely the wrong rabbit hole…

sizeof(struct Database) is giving me a size of 130200 bytes and after
compiling the program and running from terminal like so:
.\exercise17.exe db.dat c
a new file appears in my workspace, called db.dat and with size
130201 bytes according to windows properties.

Problems arise after trying out the other actions like ‘s’, ‘g’, ‘l’ &c.

Seems the right sized file is there, so why the EOF error?

Hi @johannes90,
It’s impossible to tell what’s going on without the code, and since the code in the book is known to work it’s no use for us to dig it out. Please post the relevant parts of your version, there might be subtle differences that you haven’t found. Did you diff it against the original?

A free service run by Zed A. Shaw for learncodethehardway.org.