Thursday, November 25, 2010

libiniparser sample

Ini-file:

# File: hpc-poisson.ini
#
# The file was created to examine what is libiniparser.
#
# The need to parse ini-files comes from the problem of testing
# Poisson's equation solver for various grids and number of processors.
#
# Note, that keywords and names of sections are lowercased.

# Some comments here look stupid - their purpose is demonstrate
# what is comment in ini-file.

[Test1]     ; Test #1
N1 = 64     ; Number of grid intervals in each direction
N2 = 128
N3 = 256

L1 = 1.0    ; The length of the domain in each direction
L2 = 2.0
L3 = 4.0

[TEST2]     ; Test #2
n1 = 640
n2 = 1280
n3 = 2560

l1 = 1.5
l2 = 2.5
l3 = 4.5

Source code:

/* File: main.c */

/* gcc -Wall -Wextra main.c -liniparser */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include <iniparser.h>

int main()
{
    const char *ini_fname;
    dictionary *dict;
    int num_secs;   /* Number of sections in ini file */
    int curr_sec;   /* Index of current section */

    ini_fname = "hpc-poisson.ini";
    dict = iniparser_load(ini_fname);
    assert(dict);

    num_secs = iniparser_getnsec(dict);
    printf("{number of sections: %d}\n", num_secs);

    for (curr_sec = 0; curr_sec < num_secs; ++curr_sec)
    {
        char *section;
        const char *keyword;
        char *key;  /* The value of this var is constructed as "section:keyword" */
        int val;

        /* Get name of the current section */
        section = iniparser_getsecname(dict, curr_sec);
        assert(section);
        printf("[%s]\n", section);

        /* Construct key[] */
        keyword = "n2";
        key = malloc(
                (strlen(section) + strlen(":") + strlen(keyword) + strlen("\0")) *
                sizeof(key[0])
        );
        sprintf(key, "%s:%s", section, keyword);

        /* Get value associated with the key */
        val = iniparser_getint(dict, key, -1);
        printf("%s=%d\n", keyword, val);
        free(key);
    }

    iniparser_freedict(dict);

    return EXIT_SUCCESS;
}

No comments:

Post a Comment