2008-09-28 93 views
0

我無法使用Get*Profile函數,因爲我使用的是舊版本的Windows CE平臺SDK,它沒有這些文件。它不必太籠統。如何讀取INI文件中的配置文件條目

[section] 
name = some string 

我只需要打開文件,檢查是否存在「部分」,以及與「名稱」相關的值。標準C++是首選。

回答

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; 
     } 
    } 
    } 
} 
2

你應該看看Boost.Program_options。 它有一個parse_config_file函數來填充變量的映射。正是你需要的!