1

我一直在将 libconfig 用于项目中的配置文件。当我通过 source_to_use 从源中删除双引号时,config_read_file() 返回 config_true 并且还有语法错误。语法错误将导致我的 source_to_use 选项的 getter 转到默认情况。也正因为如此,我的源数组的 getter 也将转到 else 案例。这可能只是我用 libconfig 格式犯了一个简单的语法错误吗?

这是我正在使用的配置文件:

#config for walld

#colors
colors = TRUE;

source_to_use: "sources";

default:
[
    "/home/seth/Pictures/kimi.png"
];

sources:
[
    "/home/seth/.walld/persona",
    "/home/seth/.walld/image-urls"
];

这是我读到的功能:

settings* read_config(const char* config_file, const char* home_dir) {
    settings* options = malloc(sizeof(settings));

    config_t config;
    config_setting_t* setting;
    const char* source;
    int colors;

    config_init(&config);

    if (config_read_file(&config, config_file) == CONFIG_TRUE) {
        config_destroy(&config);
        return NULL;
    }

    if (config_lookup_bool(&config, "colors", &colors)) {
        options->colors = colors;
    }
    else {
        options->colors = 0;
    }

    if (config_lookup_string(&config, "source_to_use", &source)) {
        //NOP
    }
    else {
        source = "default";
    }

    setting = config_lookup(&config, source);

    if (setting != NULL) {
        int count = config_setting_length(setting);

        linked_node* entry_point = add_node_to_list(NULL, NULL);

        linked_node* current = entry_point;

        options->sources = entry_point;


        for (int i = 0; i < count; i++) {
            char* item = config_setting_get_string_elem(setting, i);

            current = add_node_to_list(current, item);
        }
    }
    else {
        options->sources = malloc(sizeof(linked_node));
        int char_count = snprintf(NULL, 0, "%s%s", home_dir, "/.walld/images");
        if (char_count <= 0) {
            //tough luck
            abort();
        }
        char* default_folder = malloc(char_count + 1U);

        if (default_folder == NULL) {
            //tough luck
            abort();
        }

        snprintf(default_folder, char_count + 1U, "%s%s", home_dir, "/.walld/images");

        options->sources->image = default_folder;
    }

    config_destroy(&config);

    return options;
}
4

1 回答 1

1

在您的read_config功能中,您的第一个if是:

if (config_read_file(&config, config_file) == CONFIG_TRUE) {
    config_destroy(&config);
    return NULL;
}

的意义if是相反的,所以NULL如果文件的读取是有效的,你将返回 a 。

所以,你想扭转这种感觉if

if (config_read_file(&config, config_file) != CONFIG_TRUE) {
    config_destroy(&config);
    return NULL;
}

或者你可以[可能]使用:

if (config_read_file(&config, config_file) == CONFIG_FALSE) { 
于 2021-06-27T04:48:39.403 回答