4

私は大学で C を学んでいます。また、「Learn C the Hard Way」でも C を学んでいます。この質問は、具体的にはLearn C the Hard Way - 演習 17 に関連しています。

私が書いたコードでは、構造体データベースが使用されています。

#define MAX_ROWS 100
...
...
struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};
...
...
struct Database {
    struct Address rows[MAX_ROWS];
}

この演習の「追加クレジット」セクションでは、「MAX_DATA と MAX_ROWS のパラメーターを受け入れるようにコードを変更し、それらを Database 構造体に格納し、それをファイルに書き込むことで、任意のサイズのデータ​​ベースを作成する」ことを求めています。

一度に 1 つずつ集中したいので、ここでは MAX_DATA を無視します。

注:ここに私の完全なコードがあります

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_DATA 512
#define MAX_ROWS 100

struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

struct Database {
    struct Address rows[MAX_ROWS];
};

struct Connection {
    FILE *file;
    struct Database *db;
};

void die(const char *message, struct Connection *conn)
{
    if(errno) {
        perror(message);
    } else {
        printf("ERROR: %s\n", message);
    }

    free(conn->file);
    free(conn->db);
    free(conn);

    exit(1);
}

void Address_print(struct Address *addr)
{
    printf("%d %s %s\n",
            addr->id, addr->name, addr->email);
}

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

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

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

    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", conn);

    return conn;
}

void Database_close(struct Connection *conn)
{
    if(conn) {
        if(conn->file) fclose(conn->file);
        if(conn->db) free(conn->db);
        free(conn);
    }
}

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

    rc = fflush(conn->file);
    if(rc == -1) die("Cannot flush database.", conn);
}

void Database_create(struct Connection *conn)
{
    int i = 0;

    for(i = 0; i < sizeof(conn->db->rows) / sizeof(*conn->db->rows); i++) {
        // make a prototype to initialize it
        struct Address addr = {.id = i, .set = 0};
        // then just assign it
        conn->db->rows[i] = addr;
    }
}

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
    struct Address *addr = &conn->db->rows[id];
    if(addr->set) die("Already set, delete it first", conn);

    addr->set = 1;

    char *res = strncpy(addr->name, name, MAX_DATA);
    addr->name[MAX_DATA - 1] = '\0';
    if(!res) die("Name copy failed", conn);

    res = strncpy(addr->email, email, MAX_DATA);
    addr->email[MAX_DATA - 1] = '\0';
    if(!res) die("Email copy failed", conn);
}

void Database_get(struct Connection *conn, int id)
{
    struct Address *addr = &conn->db->rows[id];

    if(addr->set) {
        Address_print(addr);
    } else {
        die("ID is not set", conn);
    }
}

void Database_delete(struct Connection *conn, int id)
{
    struct Address addr = {.id = id, .set = 0};
    conn->db->rows[id] = addr;
}

void Database_list(struct Connection *conn)
{
    int i = 0;
    struct Database *db = conn->db;

    for(i = 0; i < sizeof(conn->db->rows) / sizeof(*conn->db->rows); i++) {
        struct Address *cur = &db->rows[i];

        if(cur->set) {
            Address_print(cur);
        }
    }
}

int main(int argc, char *argv[])
{
    char *filename = argv[1];
    char action = argv[2][0];
    int id = 0;
    struct Connection *conn = Database_open(filename, action);

    if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]", conn);


    if(argc > 3) id = atoi(argv[3]);
    if(id >= sizeof(conn->db->rows) / sizeof(*conn->db->rows)) die("There's not that many records.", conn);

    switch(action) {
        case 'c':
            Database_create(conn);
            Database_write(conn);
            break;

        case 'g':
            if(argc != 4) die("Need an id to get", conn);

            Database_get(conn, id);
            break;

        case 's':
            if(argc != 6) die("Need id, name, email to set", conn);

            Database_set(conn, id, argv[4], argv[5]);
            Database_write(conn);
            break;

        case 'd':
            if(argc != 4) die("Need id to delete", conn);

            Database_delete(conn, id);
            Database_write(conn);
            break;

        case 'l':
            Database_list(conn);
            break;
        default:
            die("Invalid action, only: c=create, g=get, s=set, d=del, l=list", conn);
    }

    Database_close(conn);

    return 0;
}

私が最初に考えたのは、「Database」をグローバルな構造体にせず、代わりにメイン関数に入れて、プログラムの残りの部分を流れるようにすることでしたが、この変数をプログラム全体に渡さなければならないため、非常に厄介です。ただし、これにより、必要なすべての関数呼び出しでポインターを渡す必要があることに気付きました。これは、余分なクレジットが意味するものではありません。

C初心者として、何かが足りないと感じています。私が話している用語を完全には知らないので、私の質問は漠然としているかもしれません。

私の質問が明確でない場合 - どうすればこの機能を実際に追加できますか??? 私は本当に途方に暮れています。

4

1 に答える 1

2

Databaseこの演習では、次のように変更することを意味します。

struct Database {
    int max_rows;
    struct Address *rows;
};

データベースをグローバルに保つことができますが、rows内部は で動的に割り当てる必要がありますmalloc。もちろん、これを行うには、割り当てる行数を知る必要があります。MAX_DATAそれが「とのパラメーターを受け入れる」のすべてです。パラメーターを解釈MAX_ROWSするコードを追加し、に保存し、その数に基づいて割り当てます。mainmax_rowsmax_rowsstruct Databaserows

Database_loadDatabase_write、およびDatabase_closeを変更しmax_rowsて、データベース ファイルを読み書きする必要があります。は、サイズを読み取った後にDatabase_load割り当てる責任があります。は、の呼び出しを担当します。rowsmallocDatabase_closefree()rows

于 2013-03-14T05:52:23.647 に答える