You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言配置文件参数读取代码无法获取值,求修复方案

解决C语言配置文件读取失败的问题

你的代码无法进入循环的核心原因是配置文件中参数与值之间存在=符号,但当前fscanf使用的格式字符串"%s %d"仅能匹配空格分隔的两个元素。实际读取时,第一个%s会读取到ENERGY_DEMAND,下一个非空格字符是=,会被当成第二个%s的内容而非整数,导致fscanf返回值不等于2,循环直接终止。

以下是两种可行的修改方案:

方案一:修改格式字符串匹配=符号

直接调整fscanf的格式字符串,明确匹配参数 = 值的结构:

void read_configuration_file(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        fprintf(stderr, "Error: Cannot open configuration file.\n");
        exit(EXIT_FAILURE);
    }
    char parameter[100];
    int value;
    // 格式字符串适配带等号的配置行
    while (fscanf(file, "%s = %d", parameter, &value) == 2) {
        if (strcmp(parameter, "ENERGY_DEMAND") == 0) {
            energy_demand = value;
            printf("energy_demand %d\n", energy_demand);
        } else if (strcmp(parameter, "SIM_DURATION") == 0) {
            sim_duration = value;
            printf("sim_duration %d\n", sim_duration);
        } else if (strcmp(parameter, "ENERGY_EXPLODE_THRESHOLD") == 0) {
            energy_explode_threshold = value;
            printf("energy_explode_threshold %d\n", energy_explode_threshold);
        }
    }

    fclose(file);
}

该方案简单直接,适用于配置格式严格统一的场景。

方案二:逐行读取后解析(更健壮)

通过fgets逐行读取配置文件,再用sscanf解析,能兼容等号前后空格数量不固定的情况,还可轻松扩展支持注释行:

#include <string.h>

void read_configuration_file(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        fprintf(stderr, "Error: Cannot open configuration file.\n");
        exit(EXIT_FAILURE);
    }
    char line[256];
    char parameter[100];
    int value;
    // 逐行读取文件内容
    while (fgets(line, sizeof(line), file) != NULL) {
        // 跳过空行和以#开头的注释行
        if (line[0] == '\n' || line[0] == '#') {
            continue;
        }
        // 解析行内容,忽略等号前后的空格
        if (sscanf(line, "%[^=] = %d", parameter, &value) == 2) {
            // 去除参数字符串末尾的空格(%[^=]会读取等号前所有字符,包括空格)
            parameter[strcspn(parameter, " \t")] = '\0';
            if (strcmp(parameter, "ENERGY_DEMAND") == 0) {
                energy_demand = value;
                printf("energy_demand %d\n", energy_demand);
            } else if (strcmp(parameter, "SIM_DURATION") == 0) {
                sim_duration = value;
                printf("sim_duration %d\n", sim_duration);
            } else if (strcmp(parameter, "ENERGY_EXPLODE_THRESHOLD") == 0) {
                energy_explode_threshold = value;
                printf("energy_explode_threshold %d\n", energy_explode_threshold);
            }
        }
    }

    fclose(file);
}

这种方法容错性更强,适合配置格式可能有细微变化的场景。

内容的提问来源于stack exchange,提问作者MiusiZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:27:29