melonvpn/src/impl/shared/config_reader.c
2021-04-24 11:19:44 +01:00

69 lines
1.5 KiB
C

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include "config_file.h"
/*
* Example usage
FILE *fcr;
fcr = fopen("./test-read.cfg", "r");
char *ckey;
char *cval;
while(config_read(fcr, &ckey, &cval)) {
fprintf(stderr, "key: %s\nval: %s\n\n",ckey,cval);
}
fclose(fcr);
*/
keyvaluepair_t config_read(FILE *fp) {
keyvaluepair_t result;
result.key = "";
result.value = "";
result.loop = false;
// If the input file doesn't exist then just exit
if (fp == NULL) {
fprintf(stderr, "Can't read from a non-existant file");
return result;
}
// Max line length is 250
int MAX_LEN = 250;
char buffer[MAX_LEN];
// Grab a line but if there aren't any return false
if(!fgets(buffer, MAX_LEN - 1, fp)) return result;
// Find the newline and remove it
buffer[strcspn(buffer, "\n")] = 0;
// Get the char at " = " and calculate the offset
char *midchar = strstr(buffer, " = ");
int midpoint = midchar - buffer;
// Make a char array big enough for the key and copy the key into it
char keytoken[midpoint+1];
strncpy(keytoken, buffer, midpoint);
keytoken[midpoint]=0;
// Make a char array big enough for the rest and copy from 3 chars after midchar
char valtoken[MAX_LEN-midpoint+1];
strcpy(valtoken, buffer+midpoint+3);
valtoken[MAX_LEN-midpoint]=0;
// Return them via the char array pointers
result.key = malloc(midpoint+1);
result.value = malloc(MAX_LEN-midpoint+1);
strcpy(result.key, keytoken);
strcpy(result.value, valtoken);
result.loop = true;
return result;
}