如何从INI文件中读取配置文件条目

时间:2008-09-28 21:35:25

标签: c++ parsing ini

我无法使用Get*Profile函数,因为我使用的是旧版本的Windows CE平台SDK,但没有这些功能。它不必太笼统。

[section]
name = some string

我只需要打开文件,检查“section”是否存在,以及与“name”相关联的值。标准C ++是首选。

2 个答案:

答案 0 :(得分:2)

我想出了什么:

std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
  bool section=false;
  while (!file.eof())
  {
    WCHAR _line[256];
    file.getline(_line, ELEMENTS(_line));
    std::wstringstream lineStm(_line);
    std::wstring &line=lineStm.str();
    if (line.empty()) continue;

    switch (line[0])
    {
      // new header
      case L'[':
      {
        std::wstring header;
        for (size_t i=1; i<line.length(); i++)
        {
          if (line[i]!=L']')
            header.push_back(line[i]);
          else
            break;
        }
        if (header==L"Section")
          section=true;
        else
          section=false;
      }
  break;
      // comments
      case ';':
      case ' ':
      case '#':
      break;
      // var=value
      default:
      {
        if (!section) continue;

        std::wstring name, dummy, value;
        lineStm >> name >> dummy;
        ws(lineStm);
        WCHAR _value[256];
        lineStm.getline(_value, ELEMENTS(_value));
        value=_value;
      }
    }
  }
}

答案 1 :(得分:2)

你应该看看Boost.Program_options。 它有一个parse_config_file函数,用于填充变量映射。正是你需要的!

相关问题