Help improve this INI parsing code

末鹿安然 提交于 2019-12-13 00:34:29

问题


This is something simple I came up with for this question. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.

std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
  bool section=false;
  while (!file.eof())
  {
    std::wstring line;
    std::getline(file, line);
    if (line.empty()) continue;

    switch (line[0])
    {
      // new header
      case L'[':
      {
        std::wstring header;
        size_t pos=line.find(L']');
        if (pos!=std::wstring::npos)
        {
          header=line.substr(1, pos);
          if (header==L"Section")
            section=true;
          else
            section=false;
        }
      }
  break;
      // comments
      case ';':
      case ' ':
      case '#':
      break;
      // var=value
      default:
      {
        if (!section) continue;

// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
        std::wstring name, dummy, value;
        lineStm >> name >> dummy;
        ws(lineStm);
        WCHAR _value[256];
        lineStm.getline(_value, ELEMENTS(_value));
        value=_value;
      }
    }
  }
}

How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.


回答1:


// what if the name = value does not have white space?
// what if the value is enclosed in quotes?

I would use boost::regex to match for every different type of element, something like:

boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
    name = matches[1];
    value = matches[2];
}

the regular expressions might need some tweaking.

I would also replace de stream.getline with std::getline, getting rid of the static char array.




回答2:


This:

for (size_t i=1; i<line.length(); i++)
        {
          if (line[i]!=L']')
            header.push_back(line[i]);
          else
            break;
        }

should be simplified by a call to wstrchr, wcschr, WSTRCHR, or something else, depending on what platform you are on.




回答3:


// how to get a line into a string in one go?

Use the (nonmember) getline function from the standard string header.



来源:https://stackoverflow.com/questions/146943/help-improve-this-ini-parsing-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!