Hello list,
I have a pattern I commonly use in C which I've so far failed to
translate to an equivalent Vala or indeed OO equivalent. I was hoping
that those more used to thinking in such terms would be able to point me
in the right direction.
Attached is a C file which (dumbly) parses a config file with entries of
the format:
key=value
Where a given key is uniquely associated with a particular type of data
(string, int etc...)
My aim is to parse the config file data into appropriately typed
variables, but to do so using a table based lookup on the key to find
the appropriate function to parse the data and the address of the
location to place the data.
Hopefully the C is clear enough, I apologise for posting C to this list,
but I'm not confident enough of my terminology to communicate the ideas
in Vala.
I'm looking to produce a Vala class which is able to parse <some text
data> into it's own member variables, based on a table lookup. The
important bit for me isn't the parsing, it's the lookup from key to
parse function and destination for the data.
Suggestions gratefully received!
Many thanks,
Chris.
interfaces=eth1,eth0
retries=5
unparsed=value
#include <stdio.h>
#include <string.h>
#include <errno.h>
typedef int (*config_parser_fn_t)(char *, void *);
struct parse_table_entry {
char *token;
void *dest;
config_parser_fn_t parser;
};
struct config_data cd;
struct config_data {
char *interfaces;
long int retries;
};
int parse_int(char *str, void *dst) {
*((long int *)dst) = strtoul(str, NULL, 10);
return 0;
}
int parse_str(char *str, void *dst) {
*((char **)dst) = strdup(str);
return 0;
}
struct parse_table_entry pt[] = {
{ "interfaces", &cd.interfaces, parse_str },
{ "retries", &cd.retries, parse_int },
};
int main(int argc, char *argv[]) {
FILE *input;
char line[128];
input = fopen("./config_file", "r");
if (!input) {
fprintf(stderr, "Unable to open ./config_file: %s\n", strerror(errno));
return -1;
}
while (fgets(line, sizeof(line), input) != NULL) {
int i, toklen;
for (i = 0; i < sizeof(pt) / sizeof(struct parse_table_entry); i++) {
toklen = strlen(pt[i].token);
if (strncmp(pt[i].token, line, toklen) == 0) {
if (pt[i].parser(line + toklen + 1, pt[i].dest) != 0) {
fprintf(stderr, "Unexpected input. Aborting.\n");
break;
}
}
}
}
printf("interfaces: %s\n", (cd.interfaces) ? cd.interfaces : "unset");
printf("retries: %d\n", cd.retries);
fclose(input);
}
_______________________________________________
vala-list mailing list
[email protected]
http://mail.gnome.org/mailman/listinfo/vala-list