纯C实现下实现GetPrivateProfileString

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值