2013-05-21 3 views
0

부스트 속성 트리를 사용하여 섹션 내에 속성이 포함 된 파일을 "구성된"경로 이름으로 읽는 INI을 읽으려고합니다.부스트 특성 트리를 사용하여 ini 파일의 하위 섹션에서 속성을 얻는 방법은 무엇입니까?

예를 들어 내 INI 파일은 다음과 같습니다 :

[my.section.subsection1] 
someProp1=0 

[my.section.subsection2] 
anotherProp=1 

나는 다음과 같은 코드로 읽어

namespace pt = boost::property_tree; 

pt::ptree propTree; 
pt::read_ini(filePath, propTree); 
boost::optional<uint32_t> someProp1 = pt.get_optional<uint32_t>("my.section.subsection1.someProp1"); 

문제는 내가 ...

someProp1의 가치를 결코이다

첫 번째 트리 레벨을 반복 할 때 전체 섹션 이름 my.section.subsection1을 키로 봅니다. read_ini 함수를 사용하여 섹션 이름을 점으로 트리 구조로 구문 분석 할 수 있습니까?

답변

3

속성 트리에 계층을 반영하려면 사용자 지정 파서를 작성해야합니다.

INI 절편은 단일 레벨 간단한 키 값 형식 다음 INI 파서 documentation 당. [...] 모든 속성 트리가 INI 파일로 직렬화 될 수있는 것은 아닙니다.

단일 레벨 구역화 때문에 my.section.subsection1은 계층 경로가 아닌 키로 처리되어야합니다. 예를 들어, my.section.subsection1.someProp1 경로로 나눌 수 있습니다 : "."때문에

  key separator value 
.----------^---------.^.---^---. 
|my.section.subsection1|.|someProp1| 

키의 일부인 경우 boost::property_tree::string_path 형식을 다른 구분 기호로 명시 적으로 인스턴스화해야합니다. ptreepath_type typedef로 제공됩니다. 이 경우, 나는 "/"를 사용하기로 선택한 :

ptree::path_type("my.section.subsection1/someProp1", '/') 

example.ini이 포함로 :

[my.section.subsection1] 
someProp1=0 

[my.section.subsection2] 
anotherProp=1 

다음 프로그램 :

#include <iostream> 

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/ini_parser.hpp> 

int main() 
{ 
    namespace pt = boost::property_tree; 
    pt::ptree propTree; 

    read_ini("example.ini", propTree); 

    boost::optional<uint32_t> someProp1 = propTree.get_optional<uint32_t>(
    pt::ptree::path_type("my.section.subsection1/someProp1", '/')); 
    boost::optional<uint32_t> anotherProp = propTree.get_optional<uint32_t>(
    pt::ptree::path_type("my.section.subsection2/anotherProp", '/')); 
    std::cout << "someProp1 = " << *someProp1 
      << "\nanotherProp = " << *anotherProp 
      << std::endl; 
} 

는 다음을 생성합니다 출력 :

someProp1 = 0 
anotherProp = 1 
+0

답장을 보내 주셔서 감사합니다. 섹션 이름을 기반으로 계층 구조를 반영 할 수 있도록 기본 INI 파서를 확장 할 수 있습니까? – greydet

+0

@ greydet : 파서 ​​코드를 간략하게 살펴 봤지만 지나치게 복잡하지는 않았습니다. 또 다른 옵션은 파싱을 무시하고 계층 적 "ptree"로 /부터 단일 레벨'ptree '를 확장 및/또는 평평하게 할 수 있습니다. –