C语言读取配置文件的内容

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define path "C:/Users/ZS/Desktop/test.ini"
 
//去除字符串的左右两端的空格
char *s_trim(char *str);
 
//实现读取配置文件的一行,当行的开头为#时则跳过这行
void readline(char *buf, int size, FILE *fp);
 
/* file 配置文件路径
 * sec 代表的是读取的是哪个配置
 * param 代表的是想要读取到的变量
 * value 将读取到的结果存入value
 * */
int readini(const char *file, const char *sec, const char *param, char *value);
 
int main()
{
    char str[20];
    int ret = readini(path, "server", "maxvalue", str);
    printf("%s", str);
}
 
//去除字符串的左右两端的空格
char *s_trim(char *str)
{
    char *s = str;
    char *copied, *tail = NULL;
    if(str == NULL || *str == '\0')
        return str;
    if((str[0]  != ' ') && (str[strlen(str)-1] != ' '))
        return str;
    for(copied = str; *str; str++){
        if(*str  != ' ' && *str != '\t' && *str != '\r' &&  *str != '\n'){
            *copied++ =  *str;
            tail = copied;
        }
        else{
            if(tail)
                *copied++ = *str;
        }
    }
    if(tail)
        *tail = 0;
    else
        *copied = 0;
    return s;
}
 
//实现读取配置文件的一行,当行的开头为#时则跳过这行
void readline(char *buf, int size, FILE *fp)
{
    char c;
    int i = 0;
    while((c = fgetc(fp)) != EOF && c != '\n' && c != '#') {
        if(i >= size)
            break;
        buf[i++] = c;
    }
    while(c != '\n' && c != EOF)
        c = fgetc(fp);
}
 
int readini(const char *file, const char *sec, const char *param, char *value)
{
    FILE *fp = NULL;
    char buf[1024];
    char *s;
    if((fp = fopen(file, "r")) == NULL)
        return -1;
    while(!feof(fp)){
        memset(buf, 0, sizeof(buf));
        readline(buf, sizeof(buf), fp);
        s_trim(buf);
        if(buf[0] != '[')
            continue;
        for(s = buf+1; *s != ']'; s++);
        *s = '\0';
        s_trim(buf+1);
        if(strcmp(sec, buf+1) != 0)
            continue;
        while(!feof(fp)){
            memset(buf, 0, sizeof(buf));
            readline(buf, sizeof(buf), fp);
            s_trim(buf);
            if(buf[0] == '[')
               break;
            if(buf[0] == '\0' || buf[0] == '#')
                continue;
            for(s=buf; *s != '='; s++);
            *s = '\0';
            s_trim(buf);
            if (strcmp(param, buf) == 0) {
                memcpy(value, s+1, strlen(s+1));
                value[strlen(s+1)] = '\0';
                fclose(fp);
                return 0;
           }
        }
    }
    printf("%s read error!", param);
    fclose(fp);
    return -1;
}

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值