INI文件的格式很简单,最基本的三个要素是:parameters,sections和comments
parameters:name = value
sections: [section]
comments: ;comments text
此配置解析为ini配置简化版,基本逻辑是读取文本每一行数据判断是否是name=value结构,然后存入map<string name, string value>。
1.
//加载配置文件并将所有配置解析出来,存入m_config_map
CConfigFileReader::CConfigFileReader(const char* filename)
{
_LoadFile(filename);
}
void CConfigFileReader::_LoadFile(const char* filename)
{
m_config_file.clear();
m_config_file.append(filename);
FILE* fp = fopen(filename, "r");
if (!fp)
{
//log_error("can not open %s,errno = %d", filename,errno);
printf("can not open %s,errno = %d", filename,errno);
return;
}
char buf[256];
for (;;)
{
char* p = fgets(buf, 256, fp);
if (!p)
break;
size_t len = strlen(buf);
if (buf[len - 1] == '\n')
buf[len - 1] = 0; // remove \n at the end
char* ch = strchr(buf, '#'); // remove string start with #
if (ch)
*ch = 0;
if (strlen(buf) == 0)
continue;
_ParseLine(buf);
}
fclose(fp);
m_load_ok = true;
}
2.
//从m_config_map中查找名字为name的配置
char* CConfigFileReader::GetConfigName(const char* name)
{
if (!m_load_ok)
return NULL;
char* value = NULL;
map<string, string>::iterator it = m_config_map.find(name);
if (it != m_config_map.end()) {
value = (char*)it->second.c_str();
}
return value;
}
3.
//修改m_config_map中信息,并将m_config_map内信息重新写入配置文件
int CConfigFileReader::SetConfigValue(const char* name, const char* value)
{
if(!m_load_ok)
return -1;
map<string, string>::iterator it = m_config_map.find(name);
if(it != m_config_map.end())
{
it->second = value;
}
else
{
m_config_map.insert(make_pair(name, value));
}
return _WriteFIle();
}
链接:TeamTalk_BlueBling
测试demo:tests/test_config.cpp