您的位置:首页 > 其它

读取配置

2016-05-09 16:33 232 查看
//#include"init.hpp"
#include<string>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

using namespace std;
typedef struct global_configure
{
string Ip;
bool Module;
unsigned int Port;
unsigned int Buffer;
unsigned int timer;
}Configure;
Configure __config;
char * GetString(char *title,char * key,char *filename)
{
FILE *fp;
char szLine[1024];
static char tmpstr[1024];
int rtnval;
int i = 0;
int flag = 0;
char *tmp;

if((fp = fopen(filename, "r")) == NULL)
{
printf("have no such file \n");
return "";
}
while(!feof(fp))
{
rtnval = fgetc(fp);
if(rtnval == EOF)
{
break;
}
else
{
szLine[i++] = rtnval;
}
if(rtnval == '\n')
{
i--;
szLine[--i] = '\0';
i = 0;
tmp = strchr(szLine, '=');

if(( tmp != NULL )&&(flag == 1))
{
if(strstr(szLine,key)!=NULL)
{
//注释行
if ('#' == szLine[0])
{
}
else
{
//找打key对应变量
strcpy(tmpstr,tmp+1);
fclose(fp);
return tmpstr;
}
}
}
else
{
strcpy(tmpstr,"[");
strcat(tmpstr,title);
strcat(tmpstr,"]");
if( strncmp(tmpstr,szLine,strlen(tmpstr)) == 0 )
{
//找到title
flag = 1;
}
}
}
}
fclose(fp);
return "";
}
unsigned int GetInt(char *title,char *key,char * filename)
{
return atoi(GetString(title,key,filename));
}
void init_(void)
{
try
{
//读取配置文件,加载全局配置
printf("enter into init\n");
FILE *fp=NULL;
fp=fopen("../config.ini","r");
if(!fp)
{
//此处后续添加日志记录错误
printf("error for open \n");
return ;
}
char buff[16]={0};
strcpy(buff,GetString("global","Ip","../config.ini"));
printf("buff is %s\n",buff);
strncpy(const_cast<char *>(__config.Ip.c_str()),GetString("global","Ip","../config.ini"),16);
}
catch(...)
{

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: