[英]I don't understand how inih works
I've been trying to read an ini file with inih lib since a few hours, and I still don't totally understand this code, especially configuration* pconfig = (configuration*)user;
几个小时以来,我一直在尝试使用 inih lib 读取 ini 文件,但我仍然不完全理解这段代码,尤其是
configuration* pconfig = (configuration*)user;
, and what are the handler function parameters for? ,以及处理程序 function 参数的用途是什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../ini.h"
typedef struct
{
int version;
const char* name;
const char* email;
} configuration;
static int handler(void* user, const char* section, const char* name,
const char* value)
{
configuration* pconfig = (configuration*)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("protocol", "version")) {
pconfig->version = atoi(value);
} else if (MATCH("user", "name")) {
pconfig->name = strdup(value);
} else if (MATCH("user", "email")) {
pconfig->email = strdup(value);
} else {
return 0; /* unknown section/name, error */
}
return 1;
}
int main(int argc, char* argv[])
{
configuration config;
if (ini_parse("test.ini", handler, &config) < 0) {
printf("Can't load 'test.ini'\n");
return 1;
}
printf("Config loaded from 'test.ini': version=%d, name=%s, email=%s\n",
config.version, config.name, config.email);
return 0;
}
user
is a "generic pointer", or "untyped pointer". user
是“通用指针”或“无类型指针”。
Dereferencing that pointer would give you a value of type void
which isn't possible.取消引用该指针会给你一个
void
类型的值,这是不可能的。
Therefore you must cast the pointer to the correct type to be able to use it.因此,您必须将指针转换为正确的类型才能使用它。
As for the arguments and what they're used for you could read the source .至于 arguments 以及它们的用途,您可以阅读源代码。
But with a little knowledge of INI files it should be easy to deduce that the section
argument is the name of a section in the file, while name
is the current value name, and value
is the value itself.但是稍微了解一下INI文件应该很容易推断出
section
参数是文件中的一个部分的名称,而name
是当前值的名称,而value
是值本身。
So assuming a section and value like所以假设一个部分和值像
[foo]
bar = something
Then section
would be "foo"
, name
would be "bar"
and value
would be "something"
.然后
section
将是"foo"
, name
将是"bar"
, value
将是"something"
。
And the user
argument is very likely the third argument passed to ini_parse
. user
参数很可能是传递给ini_parse
的第三个参数。
user
is obviously a pointer to configuration
instance you gave to ini_parse
. user
显然是指向您提供给ini_parse
的configuration
实例的指针。 void*
is only kind of type erasure for pointers available in C. void*
是 C 中可用指针的唯一类型擦除。
section
is name of section of.ini file, name
is key name, value
is key's value. section
是.ini 文件部分的名称, name
是键名, value
是键的值。
ini_parse
calls handler for every key, passing it configuration
and result of parsing iteration. ini_parse
为每个键调用处理程序,将configuration
和解析迭代的结果传递给它。 What handler does with that information, is to be defined by user of library.处理程序对该信息的处理由库的用户定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.