biffta
biffta

Reputation: 189

Reading a file into a struct

I'm working my way through the learn c the hard way book and have run into a few issues on Exercise 17. In the example code we create a custom database and write it to a file. We then read it back again in order to edit it.

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;
}

It appears I can create the database ok (in mode 'c') but when I go back to try and read it

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 is always 0.

I have tried lots of experiments reading a writing files and the closest I've come to getting it to work is to read the file as binary i.e.

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

That causes rc to not be 0 however it seems to corrupt other parts of the program.

Does anyone else have any thing else I could try? The only other thing I need to mention is I am building on Visual Studio 2013 and the example code is intended for gcc, should this make a difference?

I've only included the source I think is relevant but the full code is here if it aids in answering.

Thanks!

Upvotes: 0

Views: 187

Answers (1)

Antoine C.
Antoine C.

Reputation: 3952

I don't see anything wrong in the code you posted, the fact your code is intended for gcc doesn't matter. It may be an error in your file, is it a text file or a binary file ? In the last case, you can explore it with utilities as HxD.

Good luck

Upvotes: 1

Related Questions