【发布时间】:2015-07-01 22:00:49
【问题描述】:
我正在学习教程http://c.learncodethehardway.org/book/ex17.html,“Learning C The Hard Way”,似乎名为 Database_load 的函数存在错误:
void Database_load(struct Connection *conn)
{
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if(rc != 1) die("Failed to load database.");
}
函数返回“加载数据库失败”。
我尝试使用调试器,并查看了 fread() 文档,但我无法弄清楚为什么这个函数会成功返回。
我重写了函数以打印出一些健全性检查的测试:
void Database_load(struct Connection *conn)
{
printf("Database_load(struct Connection *conn)\n");
if (conn!=0)
{
printf("conn is not null\n");
if (conn->file!=0)
{
printf("conn->file is not null\n");
}//file is not null
}//end conn is not null
//actual read from filesystem
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if (!conn->db!=0)
{
printf("conn->db is not null\n");
}//db is not null
if(ferror(conn->file))
{
printf("Error in reading from file\n");
}
if(rc != 1) die("Failed to load database.");
}
下面是cmd输入:
PS C:\Users\xyz\workspace_cpp\the_hard_way\ex17> .\ex_17.exe db.dat s 1 ary ary@yahoo.com
这是程序输出:
Database_load(struct Connection *conn)
conn is not null
conn->file is not null
ERROR: Failed to load database.
我该如何进一步探索这个问题,可能是什么导致了这个问题?
【问题讨论】:
-
您可以使用
perror了解问题所在。 -
您检查了
conn != 0,但仍然取消引用conn,如果这与书中的内容相同,请停止阅读。