本文由来:
看到一些程序读取配置文件的代码, 动辄数千行, 滚动鼠标上下翻页就能晃晕读者。 实在是不能忍, 推荐使用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格式无限添加即可。
