Creating a simple configuration file and parser in C++

前端 未结 12 732
谎友^
谎友^ 2020-12-07 10:55

I am trying to create a simple configuration file that looks like this

url = http://mysite.com
file = main.exe
true = 0

when the program ru

12条回答
  •  情深已故
    2020-12-07 11:41

    SimpleConfigFile is a library that does exactly what you require and it is very simple to use.

    # File file.cfg
    url = http://example.com
    file = main.exe
    true = 0 
    

    The following program reads the previous configuration file:

    #include
    #include
    #include
    #include "config_file.h"
    
    int main(void)
    {
        // Variables that we want to read from the config file
        std::string url, file;
        bool true_false;
    
        // Names for the variables in the config file. They can be different from the actual variable names.
        std::vector ln = {"url","file","true"};
    
        // Open the config file for reading
        std::ifstream f_in("file.cfg");
    
        CFG::ReadFile(f_in, ln, url, file, true_false);
        f_in.close();
    
        std::cout << "url: " << url << std::endl;
        std::cout << "file: " << file << std::endl;
        std::cout << "true: " << true_false << std::endl;
    
        return 0;
    }
    

    The function CFG::ReadFile uses variadic templates. This way, you can pass the variables you want to read and the corresponding type is used for reading the data in the appropriate way.

提交回复
热议问题