[C/C++] INI

Alexandria·2024년 3월 4일
0

C lang

목록 보기
11/14
post-thumbnail

1. 환경

INI을 읽고 쓰기 편리한 라이브러리로 header only파일이라 include만 시켜주면 된다.

소스를 다운받자.

$ git clone https://github.com/Lek-sys/LeksysINI.git

2. 파싱

파싱하기 위한 파일을 만들어 본다.

[EXAMPLE1]
x = abc
y = 123
z = 1,2,3
t = true
[EXAMPLE2]
x = abc
y = 123
z = 1,2,3
t = true

섹션 이름과 의 이름을 통해 데이터에 접근할 수 있다.

GetValue에 데이터의 키 값을 전달하며 2번째 인자는 키가 없을 시 반환될 기본 값이다.

그리고 변환할 타입을 지정하여 변수로 받자.

#include "iniparser.hpp"
#include <iostream>

int main(void) {
    INI::File ft;
    if(ft.Load("example1.ini")){
        std::string x       = ft.GetSection("EXAMPLE1")->GetValue("x","").AsString();
        int y               = ft.GetSection("EXAMPLE1")->GetValue("y",0).AsInt();
        std::vector<int> z  = ft.GetSection("EXAMPLE1")->GetValue("z").AsArray().ToVector<int>();
        bool t              = ft.GetSection("EXAMPLE1")->GetValue("t",false).AsBool();

        std::cout << "x is " << x << std::endl;
        std::cout << "y is " << y << std::endl;
        for(int idx = 0; idx < z.size(); idx++) std::cout << "z[" << idx << "] is " << z[idx] << std::endl;
        std::cout << "t is " << t << std::endl;
        ...
    }
}

키 이름과 상관없이 반복문을 통해 키의 이름과 값에 접근할 수 있다.

#include "iniparser.hpp"
#include <iostream>

int main(void) {
    INI::File ft;
    if(ft.Load("example1.ini")){
        for (INI::File::sections_iter it = ft.SectionsBegin(); it != ft.SectionsEnd(); ++it)
        {
            INI::Section* sect = it->second;
            for (INI::Section::values_iter it2 = sect->ValuesBegin(); it2 != sect->ValuesEnd(); ++it2)
            {
                std::cout << it->first << " > " << it2->first << " : " << it2->second.AsString() << std::endl;
            }
        }
    }
    return 0;
}

3. INI 생성

INI 파일을 생성할 때는 섹션 이름과 키의 이름을 같이 적어주며 데이터를 전달한다.

배열을 생성 시 두번째 인자는 배열의 인덱스 위치 값이고 세번째가 데이터이다.

#include "iniparser.hpp"
#include <iostream>

int main(void) {
    INI::File ft;
    ft.SetValue("EXAMPLE1:x", "abc");
    ft.SetArrayValue("EXAMPLE1:y", 0, 1);
    ft.SetArrayValue("EXAMPLE1:y", 1, 2);
    ft.SetArrayValue("EXAMPLE1:y", 2, 3);
    ft.SetValue("EXAMPLE1:z", "xyz");
    ft.SetValue("EXAMPLE2:a", true);
    ft.Save("example2.ini");
    return 0;
}
profile
IT 도서관

0개의 댓글

관련 채용 정보