libyaml安装说明,请参照
https://github.com/yaml/libyaml
不过官网的示例,真是不太好找实现的样例,找了大半天,都不知道示例在搞啥,也许我不太深刻吧,果然国外人的思维和中国人不一样。
其次就是解决一个非常简单的事情,读这个配置,把参数取出来就可以了,其余的不要折腾。
直接上代码了。
先搞个db.yaml的文件样子
db_server: "localhost"
db_password: "test"
db_username: "abc"
national_rail_username: test
national_rail_password: wibble
languages:
- Ruby
- Perl
- Python
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
main.c
#include <stdio.h>
#include <yaml.h>
typedef struct Conf {
char* db_server;
char* db_pass;
char* db_user;
char* rail_user;
char* rail_pass;
} Conf;
Conf* readConf(char* filename) {
FILE* fh = fopen(filename, "r");
yaml_parser_t parser;
yaml_token_t token;
Conf* conf = malloc(sizeof(Conf));
if (!yaml_parser_initialize(&parser))
fputs("Failed to initialize parser!\n", stderr);
if (fh == NULL)
fputs("Failed to open file!\n", stderr);
yaml_parser_set_input_file(&parser, fh);
do {
/* As this is an example, I'll just use:
* state = 0 = expect key
* state = 1 = expect value
*/
int state = 0;
char** datap;
char* tk;
yaml_parser_scan(&parser, &token);
switch(token.type)
{
case YAML_KEY_TOKEN: state = 0; break;
case YAML_VALUE_TOKEN: state = 1; break;
case YAML_SCALAR_TOKEN:
tk = token.data.scalar.value;
if (state == 0) {
/* It's safe to not use strncmp as one string is a literal */
if (!strcmp(tk, "db_server")) {
datap = &conf->db_server;
} else if (!strcmp(tk, "db_password")) {
datap = &conf->db_pass;
} else if (!strcmp(tk, "db_username")) {
datap = &conf->db_user;
} else if (!strcmp(tk, "national_rail_username")) {
datap = &conf->rail_user;
} else if (!strcmp(tk, "national_rail_password")) {
datap = &conf->rail_pass;
} else {
printf("key: %s\n", tk);
}
} else {
*datap = strdup(tk);
}
break;
default: break;
}
if (token.type != YAML_STREAM_END_TOKEN)
yaml_token_delete(&token);
} while (token.type != YAML_STREAM_END_TOKEN);
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
return conf;
}
int main(){
char *filename = "db.yaml";
struct Conf *conf = readConf(filename);
printf("%s,%s\n",conf->db_server,conf->db_user);
return 0;
}
ok,就这样取出来就可以了。