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。實現的功能和以前是一致的,但是效率會更高一些。


免責聲明!

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



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