#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFFER_SIZE 512
// 读取配置文件函数
int ReadConfigFile(const char* filePath, const char* section, const char* key, char* value, size_t size) {
FILE* configFile = fopen(filePath, "r");
if (configFile == NULL) {
fprintf(stderr, "Error opening config file: %s\n", filePath);
return 0;
}
char buffer[MAX_BUFFER_SIZE];
char searchKey[MAX_BUFFER_SIZE];
snprintf(searchKey, MAX_BUFFER_SIZE, "[%s]", section);
int isInTargetSection = 0;
while (fgets(buffer, MAX_BUFFER_SIZE, configFile) != NULL) {
// 移除行尾的换行符
buffer[strcspn(buffer, "\n")] = '\0';
// 检查是否在目标节
if (strcmp(buffer, searchKey) == 0) {
isInTargetSection = 1;
} else if (isInTargetSection) {
// 检查是否是键值对
char* equalsSign = strchr(buffer, '=');
if (equalsSign != NULL) {
// 分割键值对
*equalsSign = '\0';
char* fileKey = buffer;
char* fileValue = equalsSign + 1;
// 去掉前后空格
while (*fileKey && (*fileKey == ' ' || *fileKey == '\t')) {
++fileKey;
}
while (*fileValue && (*fileValue == ' ' || *fileValue == '\t')) {
++fileValue;
}
// 如果找到了目标键,复制值并返回
if (strcmp(fileKey, key) == 0) {
strncpy(value, fileValue, size);
value[size - 1] = '\0'; // 确保字符串以 null 结尾
fclose(configFile);
return 1;
}
} else if (buffer[0] == '[') {
// 离开目标节
isInTargetSection = 0;
}
}
}
fclose(configFile);
return 0; // 未找到
}
int main() {
char value[MAX_BUFFER_SIZE];
if (ReadConfigFile("config.ini", "Section1", "Key1", value, sizeof(value))) {
printf("Value for Key1: %s\n", value);
} else {
printf("Key1 not found in Section1\n");
}
return 0;
}
纯C实现下实现GetPrivateProfileString
最新推荐文章于 2024-08-07 19:47:57 发布