Search code examples
clibyaml

How can I parse multiple subsequent YAML files in a C program using libyaml?


I'm writing a C program wherein multiple YAML configuration files need to be parsed at startup. Initially, I just made it work with a single file to start out simple, but now that I'm changing it to parse all available configuration files, I encountered a problem where if I just set a new input file with yaml_parser_set_input_file(), I hit an assertion where it tells me that I can only set the source once. So what gives? How can I parse multiple files?


Solution

  • I worked around this limitation by just initialising and then deleting the parser for every input file. Something like this:

    #include <yaml.h>
    
    int main(int argc, char* argv[]) {
        yaml_parser_t parser;
    
        // Initial setup logic
    
        while (files_to_process) {
            yaml_parser_initialize(&parser);
            yaml_parser_set_input_file(&parser, input);
    
            while (events_to_parse) {
                // Event processing logic
            }
    
            yaml_parser_delete(&parser);
        }        
    }
    

    This works for me. It feels like it should be possible to do this in a nicer way, but I couldn't find one.