读取到配置文件的C语言的接口达成
发布时间:2021-11-19 15:12:54 所属栏目:教程 来源:互联网
导读:为了完成读取系统中的配置文件的某个key键的值,由于使用别人的库总是不爽,而且对于格式有一定的要求,那么就自己来写一个这样的接口以供使用了。实现原理很简单,通过打开配置文件,进行一行一行的读取,对比行中是否存在key串且此key串的下一个字符是否为
为了完成读取系统中的配置文件的某个key键的值,由于使用别人的库总是不爽,而且对于格式有一定的要求,那么就自己来写一个这样的接口以供使用了。实现原理很简单,通过打开配置文件,进行一行一行的读取,对比行中是否存在key串且此key串的下一个字符是否为'=',若是,则得到'='号之后的值。 注意:此实现方法只适用于key=value这样的配置格式,而不是很多配置文件的key="value"的格式。 以下即是此接口的实现及测试代码: #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int get_conf_value(char *file_path, char *key_name, char *value) { FILE *fp = NULL; char *line = NULL, *substr = NULL; size_t len = 0, tlen = 0; ssize_t read = 0; if(file_path == NULL || key_name == NULL || value == NULL) { printf("paramer is invaild!n"); return -1; } fp = fopen(file_path, "r"); if (fp == NULL) { printf("open config file is error!n"); return -1; } while ((read = getline(&line, &len, fp)) != -1) { substr = strstr(line, key_name); if(substr == NULL) { continue; } else { tlen = strlen(key_name); if(line[tlen] == '=') { strncpy(value, &line[tlen+1], len-tlen+1); printf("config file format is invaild tlen is %d len is %dn", tlen, len); tlen = strlen(value); printf("get value is %s tlen is %dn", value, tlen); //replace enter key *(value+tlen-1) = ' |