鏈接到靜態(tài)庫(kù)
- C
頭文件使用libconfig.h
鏈接config
- C++
Win: 頭文件使用libconfig.h++
同時(shí)鏈接config++ config
config配置文件書寫規(guī)則
在 libconfig 配置文件中,不同的符號(hào) {}
, []
, 和 ()
有不同的用法矛纹,它們分別表示不同的數(shù)據(jù)結(jié)構(gòu)和配置元素或南。
-
大括號(hào)
{}
:- 大括號(hào)通常用于表示群組或字典。在配置文件中采够,它們用于將一組相關(guān)的設(shè)置分組在一起蹬癌。
- 群組是一系列設(shè)置的集合逝薪,可以包含任意數(shù)量的子設(shè)置蝴罪。
- 例如,以下是一個(gè)使用大括號(hào)定義的群組示例:
my_group = { setting1 = value1; setting2 = value2; // 更多設(shè)置... };
- 在這里虏肾,
my_group
是一個(gè)群組询微,包含了多個(gè)子設(shè)置撑毛。
-
方括號(hào)
[]
:- 方括號(hào)通常用于表示數(shù)組或列表唧领。在配置文件中斩个,它們用于定義一系列相似的設(shè)置。
- 數(shù)組是一組相同類型的值的序列做个,每個(gè)元素都可以通過索引訪問居暖。
- 例如,以下是一個(gè)使用方括號(hào)定義的數(shù)組示例:
my_array = [value1, value2, value3];
- 在這里太闺,
my_array
是一個(gè)包含多個(gè)值的數(shù)組省骂。
-
圓括號(hào)
()
:- 圓括號(hào)通常用于表示列表最住。在配置文件中涨缚,它們用于定義一組不同類型的值仗岖。
- 列表是一系列不同類型的值的序列,每個(gè)元素可以是標(biāo)量值揽祥、數(shù)組檩电、群組或其他列表府树。
- 例如奄侠,以下是一個(gè)使用圓括號(hào)定義的列表示例:
my_list = (value1, [1, 2, 3], {name = "John"});
- 在這里垄潮,
my_list
是一個(gè)包含不同類型元素的列表闷盔。
總結(jié):
-
{}
用于群組或字典弯洗,[]
用于數(shù)組,而()
用于列表逢勾。
如何讀取數(shù)組元素牡整,以my_array = [value1, value2, value3];
為例
#include <iostream>
#include <libconfig.h++>
using namespace std;
using namespace libconfig;
int main()
{
Config cfg;
cfg.readFile("example.cfg");
// 獲取根設(shè)置
const Setting& root = cfg.getRoot();
// 獲取數(shù)組
const Setting &myArray = root["my_array"];
int length = myArray.getLength();
cout << "Array elements: ";
for(int i = 0; i < length; ++i)
{
// 獲取數(shù)組中的整數(shù)值
int value = myArray[i];
cout << value << " ";
}
cout << endl;
return 0;
}
如何讀取列表元素 以my_list = (value1, [1, 2, 3], {name = "John"});
為例
#include <iostream>
#include <libconfig.h++>
using namespace std;
using namespace libconfig;
int main()
{
Config cfg;
cfg.readFile("example.cfg");
// 獲取根設(shè)置
const Setting& root = cfg.getRoot();
// 獲取列表
const Setting &myList = root["my_list"];
int length = myList.getLength();
// 遍歷列表
for(int i = 0; i < length; ++i)
{
const Setting &element = myList[i];
// 檢查元素類型
if(element.getType() == Setting::TypeInt)
{
int intValue;
element.lookupValue("value", intValue);
cout << "Integer: " << intValue << endl;
}
else if(element.getType() == Setting::TypeGroup)
{
string nameValue;
element.lookupValue("name", nameValue);
cout << "Name: " << nameValue << endl;
}
else if(element.getType() == Setting::TypeArray)
{
int arrayLength = element.getLength();
cout << "Array: ";
for(int j = 0; j < arrayLength; ++j)
{
int arrayValue;
element.lookupValue("value", arrayValue);
cout << arrayValue << " ";
}
cout << endl;
}
else if(element.getType() == Setting::TypeString)
{
string stringValue = element;
cout << "String: " << stringValue << endl;
}
// 其他類型...
}
return 0;
}