在C语言中,读取INI配置文件通常需要自己编写解析函数,或者使用第三方库。但这是一个常见的任务,所以有许多可供选择的库。
iniparser 库
如果你想一次性地读取INI文件并将其保存在内存中,我会推荐你使用 iniparser 库。它是一个用纯C写的库,可以解析INI文件,而且它的设计方式是一次性地读取整个INI文件到内存中,方便后续的值读取。
下面的代码展示了如何使用 iniparser 来读取INI文件:
#include <stdio.h>
#include "iniparser.h"
int main(int argc, char ** argv)
{
dictionary * ini;
ini = iniparser_load("test.ini");
if (ini==NULL) {
fprintf(stderr, "cannot parse file: %s\n", "test.ini");
return -1 ;
}
printf("Name: [%s]\n", iniparser_getstring(ini, "section:name", NULL));
printf("Age : [%d]\n", iniparser_getint(ini, "section:age", -1));
iniparser_freedict(ini);
return 0 ;
}
在这个代码中,我们首先使用 iniparser_load 函数一次性地加载整个INI文件,并将其保存在 dictionary 类型的结构体中。然后我们使用 iniparser_getstring 和 iniparser_getint 函数获取特定键的字符串和整数值。最后,我们使用 iniparser_freedict 函数释放加载的INI文件所占用的内存。
相关资料:
github iniparser用法和下载
iniparser用法
手动实现
#include <stdio.h>
#include <string.h>
// 写入INI文件
void write_ini(const char* filename, const char* section, const char* key, const char* value) {
FILE* file = fopen(filename, "a");
if (file == NULL) {
perror("Failed to open file");
return;
}
fprintf(file, "[%s]\n%s=%s\n", section, key, value);
fclose(file);
}
// 读取INI文件
void read_ini(const char* filename, const char* section, const char* key, char* value, size_t value_size) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
perror("Failed to open file");
return;
}
char line[256];
int section_found = 0;
while (fgets(line, sizeof(line), file) != NULL) {
if (line[0] == '[') {
// 检查是否是所需的section
if (strncmp(line + 1, section, strlen(section)) == 0 && line[strlen(section) + 1] == ']') {
section_found = 1;
} else {
section_found = 0;
}
} else if (section_found) {
// 检查是否是所需的key
char* eq = strchr(line, '=');
if (eq != NULL) {
*eq = '\0';
if (strcmp(line, key) == 0) {
strncpy(value, eq + 1, value_size - 1);
value[value_size - 1] = '\0';
break;
}
}
}
}
fclose(file);
}
int main() {
// 写入示例
write_ini("config.ini", "Settings", "Volume", "75");
// 读取示例
char value[256];
read_ini("config.ini", "Settings", "Volume", value, sizeof(value));
printf("Volume: %s\n", value);
return 0;
}