Files
pine-ini-reader/README.md
2023-03-17 04:53:50 +08:00

175 lines
3.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p align="center">
<img width="200" src="./assets/icon.png">
</p>
<h1 align="center">
Pine INI Reader
</h1>
<p align="center">
A simple INI file reading tool implemented in C89 aimed at teaching
</p>
## INI 格式
本解析器实现了 ini 格式的三种 pattern `COMMENT `注释、`SECTION`段落和`PARAMETER`参数
### Comment 注释
注释以`;`开头
```ini
; This is a comment
```
### Section
段落以`[``]`包围
```ini
[Section Name]
```
### Parameter
参数以`=`分割`key`键与`value`
```ini
KEY=VALUE
```
### 等效 JSON
```ini
; 下列的 parameter 没有写明 section会自动创建一个名为 _default 的 section
targetFps=10
[mount]
root=card0
[file]
ext=k3v
```
上面的 ini 与下面的 json 等效
```json
{
"default": {
"targetFps": "10"
},
"mount": {
"root": "card0"
},
"file": {
"ext": "k3v"
}
}
```
## 使用范例
```c
PineIniError errorRet;
PineIniFile* iniResult;
int i, j;
/* 解析 INI 文本 */
iniResult = PineIni_Parse(iniText, &errorRet);
/* 返回NULL从errorRet中读取错误信息 */
if (iniResult == NULL) {
printf("!!! ERROR !!!\n");
printf("errorMessage: %s\n", PINE_INI_ERRMSG[errorRet.errorCode]);
printf("errorCode: %d\n", errorRet.errorCode);
printf("lineNumber: %d\n", errorRet.lineNumber);
printf("line: \"%s\"\n", errorRet.lineContent);
return;
}
/* 打印 INI 结果中的 Section 数量 */
printf("Total sections = %d\n", iniResult->numSection);
/* 打印 INI 结果中的 Section*/
for (i = 0; i < iniResult->numSection; ++i) {
PineIniSection* section = iniResult->sections[i];
/* 打印 Section 的 Parameter 数量 */
printf("<%s> %d Parameters\n", section->name, section->numParam);
/* 打印 Section 的所有 Parameter */
for (j = 0; j < section->numParam; ++j) {
PineIniParameter* param = section->params[j];
printf(" %s: %s\n", param->key, param->value);
}
}
/* 释放 INI 资源 */
PineIni_Destory(iniResult);
```
## 测试
```c
/*
* Trim 测试
* 删除字符串左右的空格
* 空格定义:' ' 空格 | '\t' 制表符 | '\r' 回车符 | '\n' 换行符
*/
PutsTitle("Test: StringTrim");
test_PineIni_StringTrim();
/*
* RemoveQuotes 测试
* Trim并且删除字符串左右的引号
* 空格定义:" | '
*/
PutsTitle("Test: StringRemoveQuotes");
test_PineIni_StringRemoveQuotes();
/*
* INI 测试1无法识别的模式
* 某行的内容不是 COMMENT / SECTION / PARAMETER 其中之一
*/
PutsTitle("Test: Ini Illegal Pattern");
test_Ini_IllegalPattern();
/*
* INI 测试2PARAMETER模式中KEY未指定
* 例:`=notValidLine`
*/
PutsTitle("Test: Ini Empty Key");
test_Ini_EmptyKey();
/*
* INI 测试3Section数量过多
* 文件中的section过多超过了
* 宏 PINE_INI_MAX_NUM_SECTIONS 定义的最大数量
*/
PutsTitle("Test: Ini Section Exceed");
test_Ini_SectionExceed();
/*
* INI 测试4Parameter数量过多
* 某section的parameter过多超过了
* 宏 PINE_INI_MAX_NUM_PARAMETERS 定义的最大数量
*/
PutsTitle("Test: Ini Param Exceed");
test_Ini_Param_Exceed();
/*
* INI 测试4无错误
* 成功后打印所有的 section 和里面 parameter
*/
PutsTitle("Test: Ini Success");
test_Ini_Success();
PutsTitle("Test completed!");
```