2023-03-17 04:53:50 +08:00
2023-03-17 04:53:50 +08:00
2023-03-17 03:50:58 +08:00
2023-03-17 03:50:58 +08:00
2023-03-17 03:50:58 +08:00
2023-03-17 03:50:58 +08:00
2023-03-17 04:53:50 +08:00

Pine INI Reader

A simple INI file reading tool implemented in C89 aimed at teaching

INI 格式

本解析器实现了 ini 格式的三种 pattern COMMENT 注释、SECTION段落和PARAMETER参数

Comment 注释

注释以;开头

; This is a comment

Section

段落以[]包围

[Section Name]

Parameter

参数以=分割key键与value

KEY=VALUE

等效 JSON

; 下列的 parameter 没有写明 section会自动创建一个名为 _default 的 section
targetFps=10
[mount]
root=card0
[file]
ext=k3v

上面的 ini 与下面的 json 等效

{
    "default": {
       "targetFps": "10"
	},
    "mount": {
       "root": "card0"
	},
    "file": {
       "ext": "k3v"
	}
}

使用范例

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);

测试

/* 
 * 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!");
Description
INI file reader implement in C89
Readme 121 KiB
Languages
C 99.7%
Batchfile 0.3%