代码之家  ›  专栏  ›  技术社区  ›  1800 INFORMATION

如何从ini文件读取配置文件条目

  •  0
  • 1800 INFORMATION  · 技术社区  · 17 年前

    我不能使用 Get*Profile 因为我使用的是旧版本的Windows CE Platform SDK,但没有。不必太笼统。

    [section]
    name = some string
    

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

    2 回复  |  直到 9 年前
        1
  •  2
  •   1800 INFORMATION    17 年前

    我想到的是:

    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;
          }
        }
      }
    }
    
        2
  •  2
  •   Benoît photo_tom    17 年前

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