问题描述
在我的代码中,我使用iniparser(https://github.com/ndevilla/iniparser)来解析double,int和字符串。但是,我对解析用逗号分隔的数组感兴趣,例如
arr = val1,val2,...,valn
有没有简单快捷的方法,例如上面的解析器?
解决方法
最好的方法是建立自己的结构。 您可以在可为您的代码导入的Web结构上轻松找到。另一个不太好用的解决方案是将您的值作为空指针。当您想取回值时,可以使用void指针并将其强制转换为所需的值类型(int,double,char ect)。但这可能会与值冲突,因此您必须小心。您必须知道指针的哪个单元格中的种类值。这不是理想的方法,而是一种避免构建自己的结构的作弊方法。
,您可以使用libconfini,它具有数组支持。
test.conf:
arr = val1,val2,...,valn
test.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <confini.h>
struct my_conf_T {
size_t arrlen;
char ** arr;
};
static int my_listnr (IniDispatch * this,void * v_conf) {
#define conf ((struct my_conf_T *) v_conf)
if (ini_string_match_si("arr",this->data,this->format)) {
conf->arrlen = ini_array_get_length(this->value,INI_COMMA,this->format);
if (!conf->arrlen || !this->v_len) {
/* Array is empty */
return 0;
}
conf->arr = (char **) malloc(conf->arrlen * sizeof(char *) + this->v_len + 1);
if (!conf->arr) {
fprintf(stderr,"malloc() failed\n");
exit(1);
}
char * remnant = (char *) ((char **) conf->arr + conf->arrlen);
memcpy(remnant,this->value,this->v_len + 1);
for (size_t idx = 0; idx < conf->arrlen; idx++) {
conf->arr[idx] = ini_array_release(&remnant,this->format);
ini_string_parse(conf->arr[idx],this->format);
}
}
return 0;
#undef conf
}
int main () {
struct my_conf_T my_conf = (struct my_conf_T) { 0 };
if (load_ini_path("test.conf",INI_DEFAULT_FORMAT,NULL,my_listnr,&my_conf)) {
fprintf(stderr,"Sorry,something went wrong :-(\n");
return 1;
}
if (my_conf.arr) {
/* Do something with `my_conf.arr`... */
for (size_t idx = 0; idx < my_conf.arrlen; idx++) {
printf("arr[%zu] = %s\n",idx,my_conf.arr[idx]);
}
free(my_conf.arr);
}
return 0;
}
输出:
arr[0] = val1
arr[1] = val2
arr[2] = ...
arr[3] = valn
P.S。我恰好是作者。