【问题标题】:fread() is not returning successfullyfread() 没有成功返回
【发布时间】: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,如果这与书中的内容相同,请停止阅读。

标签: c mingw fread


【解决方案1】:

想法:

  1. 打开conn->file 的双重检查代码。 (是否开放阅读,模式"r""rb"?)
  2. 最初设置数据库结构时将 conn->file 设置为 NULL;这将有助于发现您忘记打开它的情况。
  3. 暂时将fread调用改为fread(conn->db, 1, sizeof(struct Database), conn->file)并检查返回值;查看它是否大于 0 但小于 sizeof(struct Database)
  4. 尝试致电getc(conn->file) 看看您是否获得了EOF 或字符。
  5. 报错后一定要调用perror()或者打印出strerror(errno)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2016-07-28
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多