Linux C 实现读取配置文件

项目使用了conf配置文件,本文抽取出读取配置文件的代码,由于配置选项和业务密切相关,可参考实际项目使用中做修改。

/**
读配置文件x.conf
注:配置文件必须为unix格式,即\n结尾
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
 
// 结构体
struct my_config
{
    char a[16];
    uint16_t b;
 
    uint8_t c;
 
    char d[3];
};
 
// 默认值
struct my_config * config_defaults(void)
{
    struct my_config *conf = NULL;
 
    conf = (struct my_config *)calloc(1, sizeof(*conf));
    if (conf == NULL)
    {
        return NULL;
    }
 
    // set default value
    conf->b= 100;
    conf->c= 1;
 
    return conf;
}
 
// 根据读取到的信息填充结构体
static int config_defaults(struct my_config *conf, const char *buf, char *pos, int line)
{
    if (strcmp(buf, "a") == 0)
    {
        strncpy(conf->a, pos, sizeof(conf->a));
    }
    else if (strcmp(buf, "c") == 0)
    {
        int val = atoi(pos);
        conf->c= val;
    }
    else if (strcmp(buf, "b") == 0)
    {
        int val = atoi(pos);
        conf->b= val;
    }
    else if (strcmp(buf, "d") == 0)
    {
        memcpy(conf->d, pos, 2);
        conf->d[2] = ' ';
    }
    // more ...
    return 0;
}
 
//
// 读配置文件
struct my_config* config_read(const char *fname)
{
    struct my_config *conf = NULL;
    FILE *f = NULL;
    char buf[1024] = {0};
    char *pos = NULL;
    int line = 0;
    int errors = 0;
    
    f = fopen(fname, "r");
    if (f == NULL)
    {
        printf("Could not open configuration file '%s' for reading.\n", fname);
        return NULL;
    }
    
    conf = config_defaults();
    if (conf == NULL)
    {
        fclose(f);
        return NULL;
    }
    
    while (fgets(buf, sizeof(buf), f))
    {
        line++;
 
        if (buf[0] == '#')
            continue;
        pos = buf;
        while (*pos != '\0')
        {
            if (*pos == '\n')
            {
                *pos = '\0';
                break;
            }
            pos++;
        }
        if (buf[0] == '\0')
            continue;
 
        pos = strchr(buf, '=');
        if (pos == NULL) {
            printf("Line %d: invalid line '%s'\n", line, buf);
            errors++;
            continue;
        }
        *pos = '\0';
        pos++;
        errors += config_defaults(conf, buf, pos, line);
    }
 
    fclose(f);
 
    return conf;
}
 
/
 
int main(int argc, char *argv[])
{
    const char* conf_file = "my.conf";
 
    if (argc == 2)
    {
        conf_file = argv[1];
    }
 
    struct my_config *conf = NULL;
    
    conf = config_read(conf_file);
    if (conf == NULL)
    {
        printf("failed to read file: %s\n", conf_file);
        return -1;
    }
    printf("%d %s %s\n", conf->c, conf->d, conf->a);
 
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值