尝试读取配置文件

trying to read a config file

本文关键字:配置文件 读取      更新时间:2023-10-16

对不起格式。无法弄清楚...

我将配置文件传递给程序

我正在尝试从特定参数读取一个值

我有一个cofigreader类,其中包含以下方法,用于从配置文件返回字符串,给定特定参数

我的问题,

它永远找不到参数。发现是0或-1 ....

string configReader::value(string config_file, string parameter)
{
    string value;
    char config_delimiter = '=';
    size_t found;
    file.open(config_file);
    std::string line;
    bool param_found = false;
    while(param_found == false){
        while (!file.eof())
        {       
            getline(file,line);
            logger.writetolog("INFO","Looking for " + parameter +
                         " on line "+ line); 
            found = line.find(parameter);
            logger.writetolog("INFO",int(found));
            if(found!=string::npos){
                param_found = true;
            }
        }
        param_found = true;
    }
    if (found!=string::npos)
    {   
        size_t a = line.find(config_delimiter)+1;
        logger.writetolog("INFO","Found" + parameter + 
                   "splitting string at delimter" + config_delimiter + 
                   " and return right side value");     
        value = line.substr(a);
        return value;
    }
    else
    {
        return value;
    }
    file.close();
}

更多信息。config文件读取。

toemail=someemailaddress@gmail.com
outputdir=C:tmp

configreader类,像这样

//attempt to parse out the required parameters for the program
string toemail = config.value(configFileArg,"toemail"); 

它总是返回空

找到匹配项后,您的 while (!file.eof())循环继续进行,过度编写了found的值。

您可以通过将循环更改为

来解决此问题
bool param_found = false;
while (!param_found && !file.eof()) {       
    if (getline(file,line)) {
        break;
    }
    logger.writetolog("INFO","Looking for " + parameter +" on line "+ line); 
    found = line.find(parameter);
    logger.writetolog("INFO",int(found));
    if(found!=string::npos){
        param_found = true;
        break;
    }
}

而是。(请注意,此代码删除了您的wir(param_found == false)循环。正如sftrabbit指出的那样,该循环是不必要的。)

写入循环的惯用方法是:

bool param_found = false;
while (std::getline(file,line)) //<-- this is idiomatic loop!
{                               //successfully read OR exit from the loop
    logger.writetolog("INFO","Looking for " + parameter +" on line "+ line); 
    found = line.find(parameter);
    logger.writetolog("INFO",int(found));
    if(found!=string::npos){
        param_found = true;
        break;
    }
}

写作循环时不应使用eof()

  • 为什么iostream :: eof内部被认为是错误的?
  • 从C 中读取文件的线的首选模式?

这两个主题详细讨论了这一点。