I am currently working on a game, and I get the configuration in an .ini file, and I get information with this library https://github.com/benhoyt/inih I would like to improve the readability / performance of this code, as I do not know much about good practices.
include "project.h"
// typedef struct s_server_conf {
// const char *ip;
// unsigned int port;
// } t_server_conf;
// typedef struct s_db_conf {
// const char *host;
// const char *user;
// const char *passwd;
// const char *db;
// unsigned int port;
// } t_db_conf;
// typedef struct s_conf {
// t_server_conf server;
// t_db_conf conf;
// } t_conf;
static int parse_server(t_conf *conf, const char *name, const char *value)
{
# define MATCH(n) (strcmp(name, n) == 0)
if (MATCH("ip"))
conf->server->ip = strdup(value);
else if (MATCH("port"))
conf->server->port = atoi(value);
else
return (0);
return (1);
}
static int parse_database(t_conf *conf, const char *name, const char *value)
{
# define MATCH_NAME(n) (strcmp(name, n) == 0)
if (MATCH_NAME("host"))
conf->db->host = (strdup(value));
else if (MATCH_NAME("user"))
conf->db->user = (strdup(value));
else if (MATCH_NAME("passwd"))
conf->db->passwd = (strdup(value));
else
return (0);
return (1);
}
static int handler(void *conf, const char *section, const char *name, const char *value)
{
# define MATCH_SECTION(s) (strcmp(section, s) == 0)
printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section)
;
if (MATCH_SECTION("database"))
return (parse_database((t_conf*)conf, name, value));
if (MATCH_SECTION("server"))
return (parse_server((t_conf*)conf, name, value));
return (0);
}
void clear_conf(t_conf *conf)
{
if (conf->db)
free(conf->db);
if (conf->server)
free(conf->server);
free(conf);
}
static t_conf *create_conf(void)
{
t_conf *conf;
if (!(conf = (t_conf*)malloc(sizeof(t_conf))))
return (NULL);
memset(conf, '\0', sizeof(t_conf));
if (!(conf->db = (t_db_conf*)malloc(sizeof(t_db_conf))))
{
clear_conf(conf);
return (NULL);
}
conf->db->port = 3306;
if (!(conf->server = (t_server_conf*)malloc(sizeof(t_server_conf))))
{
clear_conf(conf);
return (NULL);
}
return (conf);
}
t_conf *get_conf(void)
{
t_conf *conf;
if (!(conf = create_conf()))
return (NULL);
if (ini_parse("settings.ini", handler, conf) < 0)
{
printf("Unable to load configuration\n");
exit (1);
}
return (conf);
}