参考:标准c语言读 windows ini 文件
char* getKeyValu(char *filename, char *section, char *key)
{
char line[512] = {0};
char sectname[512] = {0};
char *skey = NULL, *valu = NULL;
char seps[] = "=";
bool flag = false, find = false;
FILE *fp = fopen(filename, "r");
assert(fp != NULL);
if( strchr(section, '[') == NULL){
strcpy(sectname, "[");
strcat(sectname, section);
strcat(sectname, "]");
} else {
strcpy(sectname, section);
}
while( fgets(line, 512, fp) != NULL ){
if( strcmp(line, "\n") == 0 ) { // 如果为空行直接跳过
continue;
}
valu = strchr(line, '\n'); // 删除换行符
if( valu != NULL ){
*valu = '\0';
} else {
do { // 跳过超过长度的行
fgets(line, 512, fp);
}while( strchr(line, '\n') != NULL );
continue;
}
if( line[0] == '#' ){ // 处理以 # 开头注释行
continue;
}
if( line[0] == '[' ){ // 以 [ 开头的行默认为“节”
if( find == false && strcmp(sectname, line) == 0 ){
find = true;
flag = true;
} else {
flag = false;
}
}
if( flag ){
skey = strtok(line, seps);
if( strcmp(skey, key) == 0 ){
fclose(fp);
return strtok(NULL, seps);
}
}
}
fclose(fp);
return key;
}