如何将一些数据从结构输入复制到同一结构的其他输入

问题描述 投票:0回答:0

如何将一些数据从结构输入复制到同一结构的其他输入

我有一个用 libconfig 写的表,其中一些表有重复的条目

是这样写的:

config.cfg

EFFECT1 = {
    id = 1
    enable = true
    group  = 1
    effect = 5
}

EFFECT2 = {
    id = 2
    enable = true
    group  = 1
    effect = 5
}

EFFECT3 = {
    id = 3
    enable = true
    group  = 2
    effect = 1
}
....

所以我没有添加新条目,而是决定在类似表中添加一个新字段

所以桌子看起来像这样

EFFECT1 = {
    id = 1
    enable = true
    other_effect = {
        EFFECT2 = {
            id = 2
            enable = true
        }   
    }
    group  = 1
    effect = 5
}

的想法是在阅读时如果

other_effect
字段中有任何条目
id
enable
字段被更改,其余字段使用相同的值

所以我有以下代码:

struct other_effect {
    int id;
    int enable;
}

struct effect_db {
    int id;
    int enable;
    struct other_effect effect[10];
    int group;
    int effect_id;
};


struct effect_db *data[50];    

int load_db() {
    struct effect_db *ef = NULL;
    config_t cfg;
    config_setting_t *setting, *enableother;
    const char *config_file_name = "config.cfg";

    config_init(&cfg);

    if (!config_read_file(&cfg, config_file_name)) {
        fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
                config_error_line(&cfg), config_error_text(&cfg));
        config_destroy(&cfg);
        return(EXIT_FAILURE);
    }

    ef = (effect_db*)calloc(1, sizeof(effect_db));

    setting = config_lookup(&cfg, "EFFECT1");
    if (setting != NULL) {
        config_setting_lookup_int(setting, "id", &ef->id);
        config_setting_lookup_bool(setting, "enable", &ef->enable);
        config_setting_lookup_int(setting, "group", &ef->group);
        config_setting_lookup_int(setting, "effect", &ef->effect_id);

    data[ef->id] = ef
    
    config_setting_t *othereffect = config_setting_get_member(setting, "other_effect");
    if (othereffect != NULL) {
        config_setting_t *effect_member = config_setting_get_member(othereffect, "EFFECT2");
        if (effect_member != NULL) {
            config_setting_lookup_int(effect_member, "id", &ef->effect[0].id);
            config_setting_lookup_bool(effect_member, "enable", &ef->effect[0].enable);
            
            ef->id = ef->effect[0].id;
            ef->enable = ef->effect[0].enable;
            
            data[ef->id] = ef
        }
    }
    
    config_destroy(&cfg);
    return(EXIT_SUCCESS);
}

void reloaddb(void) {

    for (int i = 0; i < 50; i++) {  
        if (data[i]) {
            free(data[i]);
            data[i] = NULL;
        }
    }
    load_db();
    
}

读取正确无误,代码应用正确。

现在如果我再次使用命令读取数据库,

other_effect
字段不起作用

c
© www.soinside.com 2019 - 2024. All rights reserved.