c - fread() is not returning successfully -
im following tutorial http://c.learncodethehardway.org/book/ex17.html, "learning c hard way", there seems bug function called database_load:
void database_load(struct connection *conn) { int rc = fread(conn->db, sizeof(struct database), 1, conn->file); if(rc != 1) die("failed load database."); }
the function returns "failed load database.".
i tried using debugger, , looked @ fread() docs, i'm unable figure why function returning successfully.
i rewrote function print out tests sanity check:
void database_load(struct connection *conn) { printf("database_load(struct connection *conn)\n"); if (conn!=0) { printf("conn not null\n"); if (conn->file!=0) { printf("conn->file not null\n"); }//file not null }//end conn not null //actual read filesystem int rc = fread(conn->db, sizeof(struct database), 1, conn->file); if (!conn->db!=0) { printf("conn->db not null\n"); }//db not null if(ferror(conn->file)) { printf("error in reading file\n"); } if(rc != 1) die("failed load database."); }
below cmd input:
ps c:\users\xyz\workspace_cpp\the_hard_way\ex17> .\ex_17.exe db.dat s 1 ary ary@yahoo.com
this program output:
database_load(struct connection *conn) conn not null conn->file not null error: failed load database.
how can further explore this, might causing issue?
ideas:
- double-check code opens
conn->file
. (is open reading, mode"r"
or"rb"
?) - set conn->file null when set database structure; catch case forget open it.
- temporarily change
fread
callfread(conn->db, 1, sizeof(struct database), conn->file)
, inspect return value; see if it's greater 0 lesssizeof(struct database)
. - try calling
getc(conn->file)
see if eof or character. - definitely call
perror()
or print outstrerror(errno)
after error.
Comments
Post a Comment