diff --git a/src/config.c b/src/config.c new file mode 100644 --- /dev/null +++ b/src/config.c @@ -0,0 +1,110 @@ +/** + * $Id: config.c 51 2008-01-10 00:19:39Z mbroeker $ + * $URL: http://localhost/svn/c/mcbot/trunk/src/config.c $ + * + */ + +#include +#include +#include + +#include + +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 = 0; + uc->port = 6667; + + 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; +}