#include <stdio.h>
#include <ctype.h>
#include "conf_file.h"
static CONF_ITEM * find_conf_item(CONF_ITEM * p_list,char * name)
{
CONF_ITEM * p = NULL;
for(p = p_list ; p->ci_name != NULL ; p++)
{
if(strcmp(name,p->ci_name) == 0)
return p;
}
fprintf(stderr,"ERROR: unknow var %s\n",name);
return NULL; /* 不支持变量名 */
}
static int parse_conf_line(CONF_ITEM * p_list,int line_no,char * line)
{
char * p = line;
char * val ,* name;
CONF_ITEM * p_item ;
//去掉首部空格
for(p ; *p == ' ' ; p++);
if(*p == '#')
return CL_TYPE_COMMENT;
else if(*p == '\n')
return CL_TYPE_EMPTY;
//查找=,并将其置为0,这样简单折分出变量名和变量值来
name = p;
for(; (*p!='=') && (*p!='\n') ; p++)
{
*p = tolower(*p); //顺便把变量名变成小写
}
if(*p != '=') //表示这一行没有 =
{
return CL_TYPE_UNKNOW;
}
val = p+1;
p--;
/* 截掉变量名后面空格*/
for(; *p==' ' ; p--);
*(p+1) = 0; //截断前后两段
//去掉值前的空格
for( ; *val == ' ' ; val++);
//去掉尾部的回车符
for( p = val; *p != '\n' ; p++);
if(*p == '\n')
*p = 0;
//查找name 是不是系统支持的配置项
p_item = find_conf_item(p_list,name);
if(p_item == NULL)
return CL_TYPE_UNSUPPORT;
p_item->ci_handle(name,val,p_item);
return CL_TYPE_CONFIGURE;
}
/* 配置文件*/
int init_conf_file()
{
/* 练习:自动把所有变量值赋成缺省值,用malloc分配空间*/
/* 如果是 ci_integer ,要分配一个整数,*/
}
#define MAX_CONF_LINE_LEN 1024
int parse_conf_file(CONF_ITEM * p_list,char * filename)
{
FILE * fp = NULL;
char buffer[MAX_CONF_LINE_LEN];
int line_no = 0;
int type;
//以只读的方式打开一个文本文件
fp = fopen(filename,"r");
if(fp == NULL)
{
fprintf(stderr,"open file %s failure \n",filename);
return -1;
}
while( fgets(buffer,sizeof(buffer),fp) != NULL)
{
//解释配置文件行;
type = parse_conf_line(p_list,++line_no,buffer);
switch(type)
{
default:
case CL_TYPE_UNKNOW:
fprintf(stderr,"line %d:unknow %s\n",line_no,buffer);
break;
case CL_TYPE_EMPTY:
fprintf(stderr,"line %d:empty line\n",line_no);
break;
case CL_TYPE_COMMENT:
fprintf(stderr,"line %d:comment %s\n",line_no,buffer);
break;
case CL_TYPE_CONFIGURE:
fprintf(stderr,"line %d:configure %s\n",line_no,buffer);
break;
case CL_TYPE_UNSUPPORT:
fprintf(stderr,"line %d:unsupport %s\n",line_no,buffer);
break;
}
}
fclose(fp);
}
int ci_parse_ipaddr(char * name,char * value,void * data)
{
//把value 赋给 p_item->value ...
printf("%s:name=\"%s\",value=\"%s\"\n",__FUNCTION__,name,value);
return 0;
}
int ci_parse_string(char * name,char * value,void * data)
{
printf("%s:name=\"%s\",value=\"%s\"\n",__FUNCTION__,name,value);
return 0;
}
int ci_parse_integer(char * name,char * value,void * data)
{
printf("%s:name=\"%s\",value=\"%s\"\n",__FUNCTION__,name,value);
return 0;
}
|