INI文件是一种简单的配置文件格式,通常用于存储应用程序的设置。它由节(sections)、键(keys)和值(values)组成,格式如下:
[section1]
key1=value1
key2=value2
[section2]
keyA=valueA
INI文件主要有两种类型:
在C语言中,处理INI文件通常需要手动解析文件内容。以下是一个简单的示例代码,展示如何读取INI文件中的值:
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 256
#define MAX_SECTION_LENGTH 64
#define MAX_KEY_LENGTH 64
typedef struct {
char section[MAX_SECTION_LENGTH];
char key[MAX_KEY_LENGTH];
char value[MAX_LINE_LENGTH];
} IniEntry;
void parse_ini(const char *filename, IniEntry *entries, int *entry_count) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("Failed to open file");
return;
}
char line[MAX_LINE_LENGTH];
char current_section[MAX_SECTION_LENGTH] = "";
*entry_count = 0;
while (fgets(line, sizeof(line), file)) {
// Trim leading whitespace
char *start = line;
while (*start == ' ' || *start == '\t') start++;
// Skip empty lines and comments
if (*start == ';' || *start == '#' || *start == '\n') continue;
// Check for section
if (line[start] == '[') {
sscanf(start, "[%[^]]]", current_section);
continue;
}
// Parse key-value pairs
char key[MAX_KEY_LENGTH], value[MAX_LINE_LENGTH];
if (sscanf(start, "%[^=]=%s", key, value) == 2) {
strcpy(entries[*entry_count].section, current_section);
strcpy(entries[*entry_count].key, key);
strcpy(entries[*entry_count].value, value);
(*entry_count)++;
}
}
fclose(file);
}
int main() {
IniEntry entries[100];
int entry_count = 0;
parse_ini("config.ini", entries, &entry_count);
for (int i = 0; i < entry_count; i++) {
printf("[%s] %s=%s
", entries[i].section, entries[i].key, entries[i].value);
}
return 0;
}
inih
(INI Not Invented Here),来简化解析过程。通过以上方法,可以在C语言中有效地处理INI文件,确保应用程序能够正确读取和解析配置信息。
领取专属 10元无门槛券
手把手带您无忧上云