C++读取配置文件的写法

记录一下读配置文件的写法。

读取配置文件可以利用string类提供的字符查找和分割来实现。

配置文件中的内容形式为:

filepath=/home/test/data/

string ConfigFileRead() 
{
    ifstream configFile;
    string path = "../conf/setting.conf";
    configFile.open(path.c_str());
    string strLine;
    string filepath;
    if(configFile.is_open())
    {
        while (!configFile.eof())
        {
            getline(configFile, strLine);
            size_t pos = strLine.find('=');
            string key = strLine.substr(0, pos);

            if(key == "filepath")
            {
                filepath = strLine.substr(pos + 1);            
            }            
        }
    }
    else
    {
        cout << "Cannot open config file!" << endl;
    }

    return filepath;
}

如果需要配置的内容较多,可以考虑先把读到的信息存到map中,需要的时候利用map中的find方法获取key对应的value。

配置文件中可以包含以#开头的注释信息,读的时候可以把它过滤掉。配置文件内容例如:

读入文件路径

path=/home/test/data/

void ConfigFileRead( map<string, string>& m_mapConfigInfo )
{
    ifstream configFile;
    string path = "../conf/setting.conf";
    configFile.open(path.c_str());
    string str_line;
    if (configFile.is_open())
    {
        while (!configFile.eof())
        {
            getline(configFile, str_line);
            if ( str_line.find('#') == 0 ) //过滤掉注释信息,即如果首个字符为#就过滤掉这一行
            {
                continue;
            }    
            size_t pos = str_line.find('=');
            string str_key = str_line.substr(0, pos);
            string str_value = str_line.substr(pos + 1);
            m_mapConfigInfo.insert(pair<string, string>(str_key, str_value));
        }
    }
    else
    {    
        cout << "Cannot open config file setting.ini, path: ";
        exit(-1);
    }
}

需要获取配置信息的时候可以通过:

map<string, string>::iterator iter_configMap;
    iter_configMap = m_mapConfigInfo.find("path");
    m_strBaseInputPath = iter_configMap->second;

补充:

后面用CPPcheck检查代码的时候发现提示.find() 函数的效率不高,建议改为.compare(),即:

if ( str_line.compare(0, 1, "#") == 0 )
 {
      continue;
 }

这段代码是比较字符串,从第0个位置开始比较一个字符,即比较第一个字符是不是"#", 如果相等,返回0,大于返回1,小于返回-1。实现的功能和以前是一致的,但是效率会更高一些。
原文链接: https://www.cnblogs.com/philipce/p/6617215.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/251406

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午5:16
下一篇 2023年2月14日 上午5:16

相关推荐