YAML (YAML Ain't Markup Language)은 JSON 과 같이 사람이 읽을 수 있는 데이터 직렬화 언어입니다 .
YAML-CPP는 그런 YAML 파일을 생성하고 읽을 수 있는 C++용 라이브러리입니다.
https://github.com/jbeder/yaml-cpp
GitHub - jbeder/yaml-cpp: A YAML parser and emitter in C++
A YAML parser and emitter in C++. Contribute to jbeder/yaml-cpp development by creating an account on GitHub.
github.com
YAML은 key:values 쌍을 기반으로 합니다.
아래는 테스트 용으로 작성한 YAML 파일입니다.
#config.yaml
RootNode:
ANode1:
aString: My Name
aSubNode:
- aFloat: 3.14
aSubNode2:
aFloat: 1.57
aBool: true
ANode2:
aInt : 34
ANode3:
- 1
- 2
라이브러리를 사용하기 위해서 yaml-cpp를 설치합니다.
sudo apt-get install libyaml-cpp-dev
YAML 파일 읽기
yaml 파일을 구성한 뒤 저장하면, LoadFile을 이용하여 읽을 수 있습니다.
#include <yaml-cpp/yaml.h>
int main(void)
{
YAML::Node config;
try{
config = YAML::LoadFile("./config.yaml");
} catch(YAML::BadFile &e) {
printf(" read error ! \n");
return -1;
}
}
아래는 config.yaml 파일 안 Node 아래 원하는 데이터가 있는지 확인하고 있을 시 값을 저장하여 출력해 줍니다.
if(!config["RootNode"]["ANode1"]["aString"])
{
// does not exist
return -1;
}
else
{
std::string val = config["RootNode"]["ANode1"]["aString"].as<std::string>();
std::cout << val << std::endl;
}
빌드하기 위해서 yaml-cpp 라이브러리를 추가합니다.
g++ -o test test.cpp -lyaml-cpp
배열로 선언되어 있는 노드는 아래와 같이 읽을 수 있다.
if(!config["RootNode"]["ANode3"][0])
{
// does not exist
return -1;
}
else
{
float val = config["RootNode"]["ANode3"][0].as<float>();
std::cout << val << std::endl;
}
참고 :
https://en.wikipedia.org/wiki/YAML
YAML - Wikipedia
From Wikipedia, the free encyclopedia Human-readable data serialization format YAML () (see § History and name) is a human-readable data serialization language. It is commonly used for configuration files and in applications where data is being stored or
en.wikipedia.org
'C++' 카테고리의 다른 글
[C++] 로그 남기기 (2) | 2024.01.25 |
---|---|
[백준] C++ 10809번 알파벳 찾기 (0) | 2022.03.11 |
[백준] C++ 4673번 셀프 넘버 (0) | 2022.03.07 |
[백준] C++ 4344번 평균은 넘겠지 (0) | 2022.02.28 |
[백준] C++ 8958번 OX퀴즈 (0) | 2022.02.28 |