我正在艰难地学习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/