程式語言 - GNU - C/C++ - GetPrivateProfileString



main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int GetPrivateProfileString(const char *title, const char *key, char *retbuf, const char *filename)
{
    FILE *fp = NULL;
    char *temp = NULL;
    char line[255] = {0};
    char buffer[255] = {0};
    int ch = 0, i = 0, flag = 0;

    if ((fp = fopen(filename, "r")) == NULL) {
        printf("failed to open file\n", filename);
        return -1;
    }

    while (!feof(fp)) {
        ch = fgetc(fp);
        if (ch == EOF) {
            break;
        }

        line[i++] = ch;
        if (ch != '\n') {
            continue;
        }

        line[--i] = '\0';
        i = 0;
        temp = strchr(line, '=');
        if ((temp != NULL) && (flag == 1)) {
            if (strstr(line, key) != NULL) {
                strcpy(retbuf, temp + 1);
                fclose(fp);
                return 0;
            }
        }
        else {
            strcpy(buffer, "[");
            strcat(buffer, title);
            strcat(buffer, "]");
            if (strncmp(buffer, line, strlen(buffer)) == 0) {
                flag = 1;
            }
        }
    }
    fclose(fp);
    return -1;
}

int main(int argc, char **argv)
{
    char buffer[255] = {0};

    if (GetPrivateProfileString("basic", "log", buffer, "config.ini") == 0) {
        printf("Result: %s\n", buffer);
    }
    return 0;
}

編譯、執行

$ vim config.ini
    [basic]
    log="test"

$ gcc main.c -o main
$ ./main
    Result: "test"