我想解析一個配置文件使用yaml。 我可以使用以下代碼作爲整個文件解析成功。配置文件解析使用yaml在c
#include <stdio.h>
#include <yaml.h>
int main(void)
{
FILE *fh = fopen("config/public.yaml", "r");
yaml_parser_t parser;
yaml_token_t token; /* new variable */
/* Initialize parser */
if(!yaml_parser_initialize(&parser))
fputs("Failed to initialize parser!\n", stderr);
if(fh == NULL)
fputs("Failed to open file!\n", stderr);
/* Set input file */
yaml_parser_set_input_file(&parser, fh);
/* BEGIN new code */
do {
yaml_parser_scan(&parser, &token);
switch(token.type)
{
/* Stream start/end */
case YAML_STREAM_START_TOKEN: puts("STREAM START"); break;
case YAML_STREAM_END_TOKEN: puts("STREAM END"); break;
/* Token types (read before actual token) */
case YAML_KEY_TOKEN: printf("(Key token) "); break;
case YAML_VALUE_TOKEN: printf("(Value token) "); break;
/* Block delimeters */
case YAML_BLOCK_SEQUENCE_START_TOKEN: puts("<b>Start Block (Sequence) </b>"); break;
case YAML_BLOCK_ENTRY_TOKEN: puts("<b>Start Block (Entry)</b>"); break;
case YAML_BLOCK_END_TOKEN: puts("<b>End block</b>"); break;
/* Data */
case YAML_BLOCK_MAPPING_START_TOKEN: puts("[Block mapping]"); break;
case YAML_SCALAR_TOKEN: printf("scalar %s \n", token.data.scalar.value); break;
/* Others */
default:
printf("Got token of type %d\n", token.type);
}
if(token.type != YAML_STREAM_END_TOKEN)
yaml_token_delete(&token);
} while(token.type != YAML_STREAM_END_TOKEN);
yaml_token_delete(&token);
/* END new code */
/* Cleanup */
yaml_parser_delete(&parser);
fclose(fh);
return 0;
}
但我想打印整個塊的值。例如,如果我有以下模塊:
force_tx_margin: (key token) (key token) default_value: 0x0 (value token) (key token) efuse_bit_offset: 2564 (value token) (key token) nwl_bit_offset: 484 (value token) (key token) width: 1 (value token)
我要打印的每張密鑰令牌的值令牌。 所有幫助表示讚賞。 :)
你想存儲整個塊的鍵值並在塊結束時打印它們嗎? –
@ParhamAlvani是的.. – RajviK