src/config.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Dec 2008 15:38:37 +0100
changeset 6 7eb12be31bb5
parent 0 586472add385
child 10 311ea5fa60dd
permissions -rw-r--r--
Various Bug Fixes including * connects to the proper server from the config file * feof (stream) loop is better than the prior solution Still missing / correctable * valgrind complains about uninitialized values * strdup must be freed, but i don't know where... committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 *  $Id: config.c 51 2008-01-10 00:19:39Z mbroeker $
 * $URL: http://localhost/svn/c/mcbot/trunk/src/config.c $
 *
 */

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

#include <config.h>

const
char *CONFIG_OPTIONS[] = {
    "NICK", "PASSWORD", "SERVER", "PORT",
    "CHANNEL", "TOPIC",
    NULL
};

int config (UC * uc, char *fname)
{
    FILE *f;
    char buffer[513];
    static char **line;
    char *token;
    char *value;
    int i = 0;

    if ((f = fopen (fname, "r")) == NULL)
        return -1;

    while (CONFIG_OPTIONS[i] != NULL)
        i++;

    line = calloc (i, sizeof (char *));

    /*
     * We can easily provide default values ...
     */
    uc->nick = uc->pass = uc->server = uc->channel = uc->topic = NULL;
    uc->port = 6667;

    *buffer = 0;
    fgets (buffer, 512, f);

    token = buffer;

    while (!feof (f)) {
        /*
         * eat trailing tabs
         */
        while (*token == '\t')
            token++;

        /*
         * eat trailing whitespaces
         */
        while (*token == ' ')
            token++;

        token = strtok (token, ":");

        if (token != NULL) {
            value = strtok (NULL, "\n");
            i = 0;
            while (CONFIG_OPTIONS[i] != NULL) {
                if (!strcmp (token, CONFIG_OPTIONS[i])) {
                    line[i] = malloc (strlen (value) + 1);
                    strncpy (line[i], value, strlen (value));
                }
                i++;
            }
        }
        *buffer = 0;
        fgets (buffer, 512, f);
    }

    if (fclose (f) != 0)
        return -1;

    i = 0;
    while (CONFIG_OPTIONS[i] != NULL) {
        if (line[i] != NULL)
            switch (i) {
            case 0:            /* NICK */
                uc->nick = line[i];
                break;
            case 1:            /* PASSWORD */
                uc->pass = line[i];
                break;
            case 2:            /* SERVER */
                uc->server = line[i];
                break;
            case 3:            /* PORT */
                uc->port = atoi (line[i]);
                break;
            case 4:            /* CHANNEL */
                uc->channel = line[i];
                break;
            case 5:            /* TOPIC */
                uc->topic = line[i];
                break;
            }
        i++;
    }

    if (!(uc->nick && uc->pass && uc->server && uc->channel))
        return -2;

    return 0;
}