用boost讀取配置文件


本文由來:

看到一些程序讀取配置文件的代碼, 動輒數千行, 滾動鼠標上下翻頁就能晃暈讀者。 實在是不能忍, 推薦使用boost 的 program_options來做讀取。

 

 

低效的例子:

 

 

 

700 行的讀取函數, 看看冰山一角長啥樣:

 

 

        else if(strcasecmp(sLine, "key") == 0)
        {
            int n = 0;
            if(sscanf(sTmp, "%d", &n)==1)
            {
                if(n > 0 && n < 100)
                {
                    g_conf.key = n;
                }
            }
        }

 

 

讀一個參數就要占用10行。

 

 

對比用boost:

 

struct DemoConfig
{
    string    str1;
    int        int1;
};

extern DemoConfig g_config_;

void ReadConfig(char* configPath)
{
    po::options_description desc("Allowed options");
    desc.add_options()
        ("str1",    po::value<string>(&g_config_.str1),        "str1")
        ("int1",    po::value<int>(&g_config_.int1),           "int1")
        ;

    std::ifstream settings_file(configPath);
    po::variables_map vm;
    po::store(po::parse_config_file(settings_file, desc), vm);
    po::notify(vm);
}

 

 

定義好數據結構, 每行讀取只需要一行代碼。

 

如果要讀取數組類型參數,也只需寫一行:

 

 

("domain",        po::value<vector<string> >(&g_config_.Domains)->multitoken(), "domain")

 

 

配置文件如下寫:

 

 

 

 

按domain=xxx格式無限添加即可。

 

 

 

本人暫時只用到以上兩種用法, 更多功能用到再補充, 也歡迎大家一起補充。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM