busted, but really must move along...

This commit is contained in:
Dan Buch 2011-10-12 08:04:23 -04:00
parent ab98180af0
commit 314faf66f8

37
ex17.c
View File

@ -15,9 +15,10 @@ struct Address {
};
struct Database {
size_t size;
int max_data;
int max_rows;
struct Address rows[];
struct Address *rows;
};
struct Connection {
@ -48,11 +49,19 @@ void Address_print(struct Address *addr)
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.", conn);
rewind(conn->file);
int rc = fread(&conn->db->max_rows, sizeof(int), 1, conn->file);
if(rc != 1) die("Failed to load database max_rows.", conn);
rc = fread(&conn->db->max_data, sizeof(int), 1, conn->file);
if(rc != 1) die("Failed to load database max_data.", conn);
rc = fread(conn->db->rows, sizeof(struct Address), conn->db->max_rows, conn->file);
if(rc != 1) die("Failed to load database rows.", conn);
}
struct Connection* Database_open(const char *filename, char mode)
struct Connection* Database_open(const char *filename, char mode, int max_rows)
{
struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn) die("Memory error", conn);
@ -60,6 +69,11 @@ struct Connection* Database_open(const char *filename, char mode)
conn->db = malloc(sizeof(struct Database));
if(!conn->db) die("Memory error", conn);
size_t rowsize = max_rows * sizeof(struct Address);
conn->db->size = rowsize;
conn->db->rows = malloc(rowsize);
if(!conn->db->rows) die("Memory error", conn);
if(mode == 'c') {
conn->file = fopen(filename, "w");
} else {
@ -88,8 +102,17 @@ void Database_write(struct Connection *conn)
{
rewind(conn->file);
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
if(rc != 1) die("Failed to write database.", conn);
int rc = fwrite(&conn->db->size, sizeof(size_t), 1, conn->file);
if(rc != 1) die("Failed to write database size.", conn);
rc = fwrite(&conn->db->max_rows, sizeof(int), 1, conn->file);
if(rc != 1) die("Failed to write database max_rows.", conn);
rc = fwrite(&conn->db->max_data, sizeof(int), 1, conn->file);
if(rc != 1) die("Failed to write database max_data.", conn);
rc = fwrite(conn->db->rows, conn->db->size, 1, conn->file);
if(rc != 1) die("Failed to write database rows.", conn);
rc = fflush(conn->file);
if(rc == -1) die("Cannot flush database.", conn);
@ -170,7 +193,7 @@ int main(int argc, char *argv[])
sscanf(argv[2], "%c:%d,%d", &action, &max_data, &max_rows);
}
struct Connection *conn = Database_open(filename, action);
struct Connection *conn = Database_open(filename, action, max_rows);
int id = 0;
if(argc > 3) id = atoi(argv[3]);