Setting key=value pairs using C

Hi,

I was wondering if there was a simpler way to use key=value pairs in C programming. I have a parser for an ini file that will create the pairs. I also need default values at run time

Here's my actual snippet.

snippet.h:
1
2
3
4
5
6
7
8
9
10
11
struct SettingsKeys {
    const char key_1[56];
    const char key_2[56];
    const char key_3[56];
} SettingsKey;

struct SettingsValues {
    int value_1;
    long int value_2;
    char value_3[56];
} SettingsValue;


main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// initialize defaults
struct SettingsKeys SettingsKey = {
    "key_3",
    "key_2",
    "key_1",
};

struct SettingsValues SettingsValue = {
    0,
    56,
    "my_value"
};

// main code to use:
//  - parse ini file to see if we have to modify the default values
//  - run with retained values
// if (SettingsKey.value_1 == x)... 


This works perfectly but a bit complicated to maintain 4 declarations in both files...

Is there an easier way to declare AND initialize defaults for the pairs?
The other thing that complicates it is that values are of different types
Since you will be reading from a file you can make a pair struct of 2 strings and convert the value based on the key.

1
2
3
4
5
struct settingPair
{
     char *Key;
     char *Value;
}



settingPair sp[10];
Last edited on
In that case, to initialize defaults, I have to do:
1
2
3
4
5
6
7
8
9
10
struct settingPair pair_1 = {
    "key_1",
    "value_1"
};

struct settingPair pair_2 = {
    "key_2",
    "value_2"
};


and so on for each entry, then same thing in the header file by declaring each pair

Was hoping for a simpler approach...
Topic archived. No new replies allowed.