在C语言中获取配置文件通常涉及读取文件、解析内容并将配置值存储到程序中,以下是一个完整的示例,展示如何从INI格式配置文件中读取设置:

配置文件示例 (config.ini)
; 服务器配置 [server] host = 127.0.0.1 port = 8080 ssl_enabled = true ; 数据库配置 [database] name = mydb user = admin timeout = 30
C语言实现代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#define MAX_LINE_LENGTH 256
#define MAX_SECTION_LENGTH 50
#define MAX_KEY_LENGTH 50
typedef struct {
char host[MAX_LINE_LENGTH];
int port;
bool ssl_enabled;
char db_name[MAX_KEY_LENGTH];
char db_user[MAX_KEY_LENGTH];
int db_timeout;
} Config;
// 去除字符串首尾空白
void trim(char* str) {
char* end;
while(isspace((unsigned char)*str)) str++;
if(*str == 0) return;
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
*(end+1) = 0;
}
// 解析配置文件
bool parse_config(const char* filename, Config* config) {
FILE* file = fopen(filename, "r");
if (!file) {
perror("无法打开配置文件");
return false;
}
char line[MAX_LINE_LENGTH];
char current_section[MAX_SECTION_LENGTH] = {0};
while (fgets(line, sizeof(line), file)) {
// 移除注释和换行符
char* comment = strchr(line, ';');
if (comment) *comment = '
