读取配置

//#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 ");
        return "";
    }
    while(!feof(fp))
    {
        rtnval = fgetc(fp);
        if(rtnval == EOF)
        {
            break;
        }
        else
        {
            szLine[i++] = rtnval;
        }
        if(rtnval == ' ')
        {
            i--;
            szLine[--i] = '';
            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 ");
    FILE *fp=NULL;
    fp=fopen("../config.ini","r");
    if(!fp)
{
    //此处后续添加日志记录错误
    printf("error for open ");
    return ;
}
    char buff[16]={0};
    strcpy(buff,GetString("global","Ip","../config.ini"));
    printf("buff is %s ",buff);
    strncpy(const_cast<char *>(__config.Ip.c_str()),GetString("global","Ip","../config.ini"),16);
}    
catch(...)
{

}
}

原文地址:https://www.cnblogs.com/oracleloyal/p/5474416.html