Skip to content

Instantly share code, notes, and snippets.

@tjs-w
Last active January 5, 2016 11:04
Show Gist options
  • Save tjs-w/c4159638f8cbe985226a to your computer and use it in GitHub Desktop.
Save tjs-w/c4159638f8cbe985226a to your computer and use it in GitHub Desktop.
LEX based Config Reader
%{
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include "config.h"
static struct config *cfg;
static unsigned char key[64], value[64];
static int inline getval(unsigned char *line)
{
sscanf(line, "%s%s", key, value);
return 0;
}
%}
%%
/* Blank lines */
^[\ \t]*\n {}
/* Comments */
^#.*\n {}
/* IP Address */
ip_addr.*\n {
getval(yytext);
printf("IP address: %s\n", value);
cfg->ip = inet_addr(value);
}
/* Port */
port.*\n {
getval(yytext);
printf("Port: %s\n", value);
cfg->port = atoi(value);
}
%%
int yywrap()
{
return 1;
}
int parse_config(unsigned char *filename, struct config *config)
{
if(NULL == (yyin = fopen(filename, "r")))
{
fprintf(stderr, "%s:%u %s failed to open configuration file %s\n", \
__FILE__, __LINE__, __func__, filename);
return -1;
}
printf("*** Parsing configuration file ***\n");
cfg = config;
yylex();
printf("*** Done ***\n");
return 0;
}
#ifndef CONFIG_H
#define CONFIG_H
struct config
{
unsigned int ip;
unsigned int port;
};
#endif
#include <stdio.h>
#include "config.h"
int main()
{
struct config cfg;
if(0 != parse_config("example.cfg", &cfg))
return -1;
printf("After parsing\
\n\tIP: %u\
\n\tPort: %u\n", cfg.ip, cfg.port);
return 0;
}
# example.cfg: Configuration file
# IP
ip_addr 10.172.17.1
# Port
port 21
# End of file
all: ParseConfig
ParseConfig: config_main.c config.c
gcc config_main.c config.c -o ParseConfig
config.c: config.l
lex -o config.c config.l
clean:
rm -vf config.c ParseConfig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment