- 论坛徽章:
- 0
|
怎么一个回复的都没有哦
我自己写了个函数 简单的实现了读取配置文件的功能
大家看看 有什么问题 和 需要改进的 地方么?- #include <stdio.h>
- #include <string.h>
- /*******************************************************
- * 函数名称:ReadConfig
- * 参数列表:conf_path 配置文件路径
- conf_name 字段标识
- config_buff 数据空间
- * 返回值: 0 成功
- -1 失败
- * 函数功能:从指定的配置文件中读取需要的字段
- *******************************************************/
- int ReadConfig(char
- *conf_path,char *conf_name,char *config_buff)
- {
- char config_linebuf[256];
-
- char line_name[40];
- char exchange_buf[256];
- char *config_sign = "=";
-
- char *leave_line;
- FILE *f;
- f = fopen(conf_path,"r");
- if(f == NULL)
- {
-
- printf("OPEN CONFIG FALID\n");
- return -1;
- }
- fseek
- (f,0,SEEK_SET);
- while(fgets(config_linebuf,256,f) != NULL)
- {
- if
- (strlen(config_linebuf) < 3) //判断是否是空行
- {
- // printf("空
- 行 \n");
- continue;
- }
- if (config_linebuf
- [strlen(config_linebuf)-1] == 10) //去除最后一位是\n的情况
- {
- //
- printf("回车 \n");
- memset(exchange_buf,0,sizeof(exchange_buf));
-
- strncpy(exchange_buf,config_linebuf,strlen(config_linebuf)-1);
-
- memset(config_linebuf,0,sizeof(config_linebuf));
- strcpy
- (config_linebuf,exchange_buf);
- }
- memset(line_name,0,sizeof
- (line_name));
- leave_line = strstr(config_linebuf,config_sign);
- if
- (leave_line == NULL) //去除无"="的情况
- {
- // printf("没有等号
- \n");
- continue;
- }
- int leave_num = leave_line
- - config_linebuf;
- strncpy(line_name,config_linebuf,leave_num);
- if
- (strcmp(line_name,conf_name) ==0)
- {
- strncpy
- (config_buff,config_linebuf+(leave_num+1),strlen(config_linebuf)-leave_num-1);
-
- break;
- }
- if(fgetc(f)==EOF)
- {
-
- break;
- }
- fseek(f,-1,SEEK_CUR);
- memset
- (config_linebuf,0,sizeof(config_linebuf));
- }
- fclose(f);
- return 0;
- }
- int
- main(int argv,char *argc[])
- {
- int ret;
- char conf_path[] = "gwis.conf";
-
- char conf_start[] = "START";
- char conf_end[] = "END";
- char config_start
- [32],config_end[32];
- memset(config_start,'\0',32);
- memset(config_end,'\0',32);
- if
- (access("host",0) != -1)
- {
- printf("Find USB Media! \n");
- ret
- = ReadConfig(conf_path,conf_start,config_start);
- printf("起始日期 : %s
- \n",config_start);
- printf("ret = %d \n",ret);
- ret = ReadConfig
- (conf_path,conf_end,config_end);
- printf("结束日期 : %s \n",config_end);
-
- printf("ret = %d \n",ret);
- }
- return 0;
- }
复制代码 配置文件:
START=20130216
END=20130220
下面是输出:
Find USB Media!
起始日期 : 20130216
ret = 0
结束日期 : 20130220
ret = 0 |
|