Creating a simple configuration file and parser in C++

前端 未结 12 756
谎友^
谎友^ 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:51

    As others have pointed out, it will probably be less work to make use of an existing configuration-file parser library rather than re-invent the wheel.

    For example, if you decide to use the Config4Cpp library (which I maintain), then your configuration file syntax will be slightly different (put double quotes around values and terminate assignment statements with a semicolon) as shown in the example below:

    # File: someFile.cfg
    url = "http://mysite.com";
    file = "main.exe";
    true_false = "true";
    

    The following program parses the above configuration file, copies the desired values into variables and prints them:

    #include 
    #include 
    using namespace config4cpp;
    using namespace std;
    
    int main(int argc, char ** argv)
    {
        Configuration *  cfg = Configuration::create();
        const char *     scope = "";
        const char *     configFile = "someFile.cfg";
        const char *     url;
        const char *     file;
        bool             true_false;
    
        try {
            cfg->parse(configFile);
            url        = cfg->lookupString(scope, "url");
            file       = cfg->lookupString(scope, "file");
            true_false = cfg->lookupBoolean(scope, "true_false");
        } catch(const ConfigurationException & ex) {
            cerr << ex.c_str() << endl;
            cfg->destroy();
            return 1;
        }
        cout << "url=" << url << "; file=" << file
             << "; true_false=" << true_false
             << endl;
        cfg->destroy();
        return 0;
    }
    

    The Config4Cpp website provides comprehensive documentation, but reading just Chapters 2 and 3 of the "Getting Started Guide" should be more than sufficient for your needs.

提交回复
热议问题