#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LINE_MAX 256
void parse_line(char *line) {
char *p = NULL;
char var[LINE_MAX] = {'\0'}; // zero-out the memory for easy use memcpy
char val[LINE_MAX] = {'\0'}; // ditto
size_t len =0;
p = strchr(line, '\n'); // assumes unix line ending
if(p != NULL) {
*p = '\0';
}
len = strlen(line);
p = strchr(line, '=');
if(p == NULL) {
fprintf(stderr, "\'%s\' is a parse error\n", line);
return;
}
// get the part before the first =
memcpy(var, line, p - line);
// skip the actual '=' sign
p++;
// get the value of the var
memcpy(val, p, (line+len)-p);
printf("\'%s\' = \'%s\'\n", var, val); // print they were parsed OK
// you probably want to store them in a hash table or something
// do it here. parse numbers to numbers, etc etc etc...
}
void read_config(char *file) {
char line[LINE_MAX];
FILE *config = NULL;
config = fopen("./config.txt", "r");
if(config == NULL) {
fprintf(stderr, "%s", "Error opening ./config.txt\n");
exit(EXIT_FAILURE);
}
while(fgets(line, LINE_MAX, config)) {
if(line[0] == '#') { // skip comment line
continue;
}
parse_line(line);
}
fclose(config);
}
int main() {
read_config("./config.txt");
return 0;
}