配置文件

来源:百度文库 编辑:神马文学网 时间:2024/05/15 05:15:51
配置文件解析函数(C语言)
/*
*        config.h
*        This file is usred for parsing configure file.
*        E-mail : yhniejun@163.com
*        2007.01.25 Mr.Nie
*/
/*
*        the struct of config file.
*/
struct conf_info
{
const char *name;
void *object;
};
typedef struct conf_info Cconf_info;
/*
*        the function of removing the free space.
*/
static void trim(char *);
struct conf_info *lookup_keyword(char *);
static void apply_command(Cconf_info *, char *);
void parse(FILE *);
以下是调用例子:
/*
*        config.c
*        This file is usred for parsing configure file.
*        E-mail : yhniejun@163.com
*        2007.01.25 Mr.Nie
*/
#include
#include
#include
#include "config.h"
char *server_root;
char *db_addr;
char *db_user;
char *db_passwd;
struct conf_info clist[] = {
{"serverName", &server_root},
{"dbAddr", &db_addr},
{"dbUser", &db_user},
{"dbPasswd", &db_passwd},
};
static void trim(char *s)
{
char *c = s + strlen(s) - 1;
while (isspace(*c) && c > s) {
*c = ‘\0‘;
--c;
}
}
struct conf_info *lookup_keyword(char *c)
{
struct conf_info *p;
for (p = clist; p < clist + (sizeof (clist) / sizeof (struct conf_info)); p++)
{
if (strcasecmp(c, p->name) == 0)
return p;
}
return NULL;
}
static void apply_command(Cconf_info * p, char *args)
{
if (p->object) {
if (*(char **) p->object != NULL)
free(*(char **) p->object);
*(char **) p->object = strdup(args);
}
}
/*    parse configure file        */
void parse(FILE * fp)
{
Cconf_info *p;
char buf[1025], *c;
int line = 0;
while (fgets(buf, 1024, fp) != NULL)
{
++line;
if (buf[0] == ‘\0‘ || buf[0] == ‘#‘ || buf[0] == ‘\n‘)
continue;
trim(buf);
if (buf[0] == ‘\0‘)
continue;
c = buf;
while (!isspace(*c))
++c;
if (*c == ‘\0‘) {
c = NULL;
}
else {
*c = ‘\0‘;
++c;
}
p = lookup_keyword(buf);
apply_command(p, c);
}
}
#include
#include
#include "config.h"
extern char *server_root;
extern char *db_addr;
extern char *db_user;
extern char *db_passwd;
int main(void)
{
FILE *fp;
if ((fp = fopen("test.conf", "r")) == NULL)
{
fprintf(stderr, "Can‘t open conf file %s .\n", "test.conf");
exit(3);
}
parse(fp);
printf("ServerRoot is : %s\n", server_root);
printf("DataBase address is : %s\n", db_addr);
printf("DataBase user is : %s\n", db_user);
printf("DataBase user password is : %s\n", db_passwd);
return 0;
}
以下是Makefile文件:
config : config_test.o config.o
cc -o config config_test.o config.o
#config.o : config.c config.h
config_test.o : config_test.c
config.o : config.c
clean :
-rm *.o config
#######配置文件test.conf######
#
serverName 10.10.206.30
dbAddr 10.10.206.32
dbUser root
dbPasswd 123456
####
##