c - 将文件读入结构体

标签 c

我正在艰难地学习c book在练习 17 中遇到了一些问题。在示例代码中,我们创建一个自定义数据库并将其写入文件。然后我们再次读回它以进行编辑。

struct Connection *Database_open(const char *filename, char mode)
{
    struct Connection *conn = malloc(sizeof(struct Connection));
    if (!conn) die("Memory error");

    conn->db = malloc(sizeof(struct Database));
    if (!conn->db) die("Memory error");

    if (mode == 'c') {
        conn->file = fopen(filename, "w");
    }
    else {
        conn->file = fopen(filename, "r+");
        if (conn->file) {
            Database_load(conn);
        }
    }

    if (!conn->file) die("Failed to open the file");

    return conn;
}

看来我可以正常创建数据库(在模式“c”下),但是当我回去尝试读取它时

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.");
}

rc 始终为 0。

我尝试了很多读取写入文件的实验,最接近的方法是将文件读取为二进制文件,即

    else {
        conn->file = fopen(filename, "rb+");

这会导致 rc 不为 0,但它似乎会破坏程序的其他部分。

还有其他人可以尝试的其他方法吗?我需要提及的唯一一件事是我正在 Visual Studio 2013 上构建,并且示例代码适用于 gcc,这应该有所不同吗?

我只包含了我认为相关的来源,但 full code is here如果对回答有帮助的话。

谢谢!

最佳答案

我没有发现您发布的代码有任何问题,您的代码适用于 gcc 的事实并不重要。 您的文件可能有错误,它是文本文件还是二进制文件?在最后一种情况下,您可以使用 HxD 等实用程序来探索它。

祝你好运

关于c - 将文件读入结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22000809/

相关文章:

c - char指针零是什么意思?

c - 不知道如何将 Java 类转换为 C 头文件和代码

c - Eclipse Kepler 中 undefined reference

c - 在 GLib 中搜索 g_slist_find_custom() 函数

c - 如何让 GCC 在进行函数调用时警告参数数量不匹配?

c - stat() 返回错误

回调未在编辑控件上触发

c - 如何在不等待用户输入的情况下从 stdin 获取字符?

C: sscanf 问题后局部指针变量改变

c - 打印负数