在我的代码中,我使用了iniparser (https://github.com/ndevilla/iniparser)来解析双精度、整型和字符串。但是,我对解析用逗号分隔的数组感兴趣,比如
arr = val1, val2, ..., valn有没有什么简单快捷的方法,像上面的解析器?
发布于 2020-09-15 16:32:39
最好的方法是制作自己的结构。你可以很容易地在web结构上找到你可以为你的代码导入的。另一个不太好的解决方案是将你的值作为空指针。当你想取回你的值时,你可以使用void指针,并将它转换成你想要的值( int,double,char等)。但这可能会与值冲突,因此您必须小心。您必须知道指针的哪个单元格中是什么类型的值。这不是理想的方式,但这是一种避免制作自己的结构的欺骗方式。
发布于 2020-10-07 10:06:19
您可以使用libconfini,它支持数组。
test.conf:
arr = val1, val2, ..., valntest.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, INI_COMMA, 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另外,我碰巧是作者。
https://stackoverflow.com/questions/63897298
复制相似问题