Variable Update from Config File in C
Today's problem is related with update of variables from the configuration file. The variables and their corresponding user values are saved in a config file and when a program is run, these variables are updated with user define values. The complete code regarding this problem is given below:
#include <stdio.h>
/*Create structure of variable with default initial values*/
struct variables {
int DATA_SIZE;
int ATTEN_DATES;
int MAX_LINE_CHAR;
} config_var = {30, 31, 1024};
char *cleanTxt(char *str) {
char *txt = malloc(config_var.DATA_SIZE);
int i = 0, j = 0, lf = 0, rf = 0;
while (str[i] != '\0') {
/*If string starts with space, do *
*not copy space characters into txt*/
if (str[i] == ' ' && lf == 0) {
} else {/*Otherwise copy the character*/
txt[j] = str[i];
lf = 1;
j++;
}
i++;
}
txt[i] = '\0';
i = strlen(txt);
/*Remove trailing spaces, string terminating, new*
*line or return carriage symbols. Do it till *
*alpha numeric character is not found. */
while (i >= 0) {
if (txt[i] == ' ' \
|| txt[i] == '\0' \
|| txt[i] == '\n' \
|| txt[i] == '\r') {
txt[i] = '\0';
} else {
break;
}
i--;
}
return txt;
free(txt);
}
void setKeyValue(char *k, char * v) {
if (strcmp(k, "DATA_SIZE") == 0) {
config_var.DATA_SIZE = atoi(v);
}
if (strcmp(k, "ATTEN_DATES") == 0) {
config_var.ATTEN_DATES = atoi(v);
}
}
int main(void) {
FILE *fconfig;
char *line = malloc(config_var.MAX_LINE_CHAR);
char key[config_var.MAX_LINE_CHAR];
char value[config_var.MAX_LINE_CHAR];
fconfig = fopen("config.f", "r");
if (!fconfig) {
printf("Unable to load configuration file???\n");
return 0;
}
int i = 0, l = 0;
if (fconfig) {
while (fgets(line, config_var.MAX_LINE_CHAR, fconfig)) {
if (line[0] != '#' && strlen(cleanTxt(line)) > 0) {
i = 0, l = 0;
while (line[l] != '=') {
key[i] = line[l];
l++;
i++;
}
key[i] = '\0';
i = 0;
l++;
while (line[l] != '\0') {
value[i] = line[l];
l++;
i++;
}
value[i] = '\0';
setKeyValue(key, value);
}
}
free(line);
}
fclose(fconfig);
printf("%d\n", config_var.DATA_SIZE);
printf("%d\n", config_var.ATTEN_DATES);
return 0;
}
............config.f file data............
DATA_SIZE=30
#ATTEN_DATES=30
ATTEN_DATES=33