Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1409042
  • 博文数量: 430
  • 博客积分: 9995
  • 博客等级: 中将
  • 技术积分: 4388
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-24 18:04
文章存档

2013年(1)

2008年(2)

2007年(14)

2006年(413)

分类:

2006-06-27 12:44:45



test.ini

dbsybase
ip=192.168.1.4
dbname=sa
dbpassword=test

--------------------------------
testini.c

#include
#include
#include
int main(int argv,char **argc)
{
FILE *ini;
char *name,*value,line[100];
if(argv!=2)
{
printf("Usage:%s *.ini\n",argc[0]);
exit(1);
}
ini=fopen(argc[1],"r");
while(!feof(ini))
{
 fgets(line,1024,ini);
 name=strtok(line,"=");
 value=strtok(0,"=");
 if(name&&value)
 printf("name=%s value=%s",name,value);
 else
 {
 printf("read %s error\n",argc[0]);
 }
}
printf("\n");
return 0;
}


 

--------------------------------------------------------------------------------
 bbllyy 回复于:2004-09-23 11:40:18
有没有改写init的程序?楼主写得不错啊

 

--------------------------------------------------------------------------------
 梦蓝 回复于:2004-09-23 18:07:31
这个程序还有很多缺陷,我写了一些代码,大家指正。

/*rwcfg.h*/
#ifndef RW_CFG_H
#define RW_CFG_H

#define MAX_LINE_LENGTH  1024

#define COMMENT_FLAG            0x23   /* .config/.ini file comment symbol # */

#define SECTION_START_FLAG      0x5B
#define SECTION_END_FLAG        0x5D   /* .config/.ini file section symbol []*/

#define KEY_FLAG                0x3D   /* .config/.ini file key symbol =     */


struct cfgline{
        int  nType;
        char *pcName;
        char *pcValue;
        char *pcComment;

        struct cfgline *next;
};
typedef struct cfgline linenode;
typedef linenode *linelink;

linelink fInitCfg(char *filename);
void fFormatCfg(char *filename);
void fCloseCfg(linelink head);
void fWriteCfg(char *filename,linelink head);

char *getKey(linelink head,char *secName,char *keyName);
int addKey(const linelink head,const char *secName,const char *keyName,const char *keyValue);
int modifyKey(const linelink head,const char *secName,const char *keyName,const char *newValue);

 

--------------------------------------------------------------------------------
 梦蓝 回复于:2004-09-23 18:09:48
/*rwcfg.c*/
#include "analyse.h"
#include "rwcfg.h"

/* ------------------------------------------------------------------------- */
/*
>0 OK
-1 EOF
-2 ERROR
*/
int  fReadLine(FILE *fp, char *buffer) 

int  i=0; 

   if(fgets(buffer, MAX_LINE_LENGTH, fp) == NULL) 
   { 
     i = strlen(buffer); 
     if(feof(fp) != 0) 
     { 
       if(i == 0) return -1;           /* EOF */ 
     } 
     else return -2;                         /* error */ 
   } 

   i = strlen(buffer); 
  
if(i > 0 && buffer[i-1] == '\n') 
     buffer[--i] = '\0'; 

return i;  

/* ------------------------------------------------------------------------- */
linelink fInitCfg(char *pcFileName)
{
FILE *fp;
linelink head,ptr;

head=ptr=NULL;

assert(pcFileName!=NULL);

fp = fopen(pcFileName, "r");
assert(fp!=NULL);

char buffer[MAX_LINE_LENGTH+1];
memset(buffer,0x00,MAX_LINE_LENGTH+1);

while((fReadLine(fp,buffer)>=0)&&(!feof(fp))) 
{
char bufName[MAX_LINE_LENGTH+1];
char bufValue[MAX_LINE_LENGTH+1];
char bufComment[MAX_LINE_LENGTH+1];

memset(bufName,0x00,MAX_LINE_LENGTH+1);
memset(bufValue,0x00,MAX_LINE_LENGTH+1);
memset(bufComment,0x00,MAX_LINE_LENGTH+1);

int nType=strAnalyse(bufName,bufValue,bufComment,buffer,MAX_LINE_LENGTH);

if(nType>0)
{
char *pcName=NULL;
                 char *pcValue=NULL;
                 char *pcComment=NULL;

linelink t=(linelink)malloc(sizeof(linenode));
                 assert(t!=NULL);

t->nType=nType;
                 t->pcName=NULL;
                 t->pcValue=NULL;
                 t->pcComment=NULL;
t->next=NULL;

if(((nType==1)||(nType==2))&&(bufName[0]!='\0'))
{
pcName=(char *)malloc(sizeof(char)*(strlen(bufName)+1));
assert(pcName!=NULL);

strcpy(pcName,bufName);
pcName[strlen(bufName)+1]='\0';

t->pcName=pcName;
}

if((nType==2)&&(bufValue[0]!='\0'))
                        {
                                pcValue=(char *)malloc(sizeof(char)*(strlen(bufValue)+1));
                                assert(pcValue!=NULL);

                                strcpy(pcValue,bufValue);
                                pcValue[strlen(bufValue)+1]='\0';

                                t->pcValue=pcValue;
                        }

if(bufComment[0]!='\0')
{
pcComment=(char *)malloc(sizeof(char)*(strlen(bufComment)+1));
                                assert(pcComment!=NULL);

                                strcpy(pcComment,bufComment);
                                pcComment[strlen(bufComment)+1]='\0';

                                t->pcComment=pcComment;
}

if(head==NULL)
{
head=t;
ptr=t;
}
else
{
ptr->next=t;
ptr=t;
  }
}    
}

fclose(fp);

return head;
}

/* ------------------------------------------------------------------------- */
void fCloseCfg(linelink head)
{
linelink ptr=head;

while(ptr!=NULL)
{
linelink temp=ptr;
ptr=ptr->next;

if(temp->pcName!=NULL) free(temp->pcName);
if(temp->pcValue!=NULL) free(temp->pcValue);
if(temp->pcComment!=NULL) free(temp->pcComment);

free(temp);
}

head=NULL;

/* ------------------------------------------------------------------------- */
void fWriteCfg(char *filename,linelink head)
{
assert(head!=NULL);

FILE *fp;
        linelink ptr=head;

        fp = fopen(filename, "w");
        assert(fp!=NULL);
                
        while(ptr!=NULL)
        {
                char buf[MAX_LINE_LENGTH+1];
memset(buf,0x00,MAX_LINE_LENGTH+1);

int i=0;
int j=0;
if(ptr->nType==1)
{
buf[i++]=SECTION_START_FLAG;
for(j=0;jpcName);j++)
buf[i++]=ptr->pcName[j];
buf[i++]=SECTION_END_FLAG;

if(ptr->pcComment!=NULL)
{
buf[i++]='\t';
buf[i++]=COMMENT_FLAG;
for(j=0;jpcComment);j++)
                                 buf[i++]=ptr->pcComment[j];
}

                        buf[i]='\0';
}
else if(ptr->nType==2)
{
                        buf[i++]='\t';

for(j=0;jpcName);j++)
                                buf[i++]=ptr->pcName[j];
                        buf[i++]=' ';
buf[i++]=KEY_FLAG;
buf[i++]=' ';

for(j=0;jpcValue);j++)
                                buf[i++]=ptr->pcValue[j];

                        if(ptr->pcComment!=NULL)
                        {
                                buf[i++]='\t';
buf[i++]=COMMENT_FLAG;
                                for(j=0;jpcComment);j++)
                                        buf[i++]=ptr->pcComment[j];
                        }

                        buf[i]='\0';
                }
else
{
buf[i++]=COMMENT_FLAG;
                        for(j=0;jpcComment);j++)
                         buf[i++]=ptr->pcComment[j];
buf[i]='\0';
}

fputs(buf, fp);
                fputs("\n", fp);

                ptr=ptr->next;

if((ptr!=NULL)&&(ptr->nType==1))
fputs("\n", fp);
        }

        fclose(fp);
}

/* ------------------------------------------------------------------------- */
void fFormatCfg(char *filename)
{
assert(filename!=NULL);

linelink head=fInitCfg(filename);

fWriteCfg(filename,head);

fCloseCfg(head);
}

/* ------------------------------------------------------------------------- */
linelink locateSection(const linelink head,const char *secName)
{
assert((head!=NULL)&&(secName!=NULL));

linelink ptr=head;

while(ptr!=NULL)
{
if((ptr->nType==1)&&(strcmp(ptr->pcName,secName)==0))
return ptr;

ptr=ptr->next;
}

return NULL;
}

/* ------------------------------------------------------------------------- */
linelink locateKey(const linelink head,const char *secName,const char *keyName)
{
assert(((head!=NULL)&&(secName!=NULL))&&(keyName!=NULL));

        linelink ptr=locateSection(head,secName);

if(ptr==NULL)
return NULL;

ptr=ptr->next;
        while((ptr!=NULL)&&(ptr->nType!=1))
        {
if((ptr->nType==2)&&(strcmp(ptr->pcName,keyName)==0))
                        return ptr;

                ptr=ptr->next;
        }

        return NULL;
}

/* ------------------------------------------------------------------------- */
char *getKey(linelink head,char *secName,char *keyName)
{
        assert(((head!=NULL)&&(secName!=NULL))&&(keyName!=NULL));

linelink ptr=locateKey(head,secName,keyName);

        if(ptr==NULL)
                return NULL;
else
                return ptr->pcValue;
}

/* ------------------------------------------------------------------------- */
int modifyKey(const linelink head,const char *secName,const char *keyName,const char *newValue)
{
        assert(((head!=NULL)&&(secName!=NULL))&&((keyName!=NULL)&&(newValue!=NULL)));

        linelink ptr=locateKey(head,secName,keyName);

        if(ptr==NULL)
                return -1;
        else
{
free(ptr->pcValue);
ptr->pcValue=(char *)malloc(sizeof(char)*(strlen(newValue)+1));                
memset(ptr->pcValue,0x00,sizeof(char)*(strlen(newValue)+1));
strcpy(ptr->pcValue,newValue);

return 0;
}
}

/* ------------------------------------------------------------------------- */
int addKey(const linelink head,const char *secName,const char *keyName,const char *keyValue)
{
        assert(((head!=NULL)&&(secName!=NULL))&&((keyName!=NULL)&&(keyValue!=NULL)));

        linelink ptr=locateSection(head,secName);

        if(ptr==NULL)
                return -1;
        else
        {
                linelink t=(linelink)malloc(sizeof(linenode));
assert(t!=NULL);

t->nType=2;

t->pcName=(char *)malloc(sizeof(char)*(strlen(keyName)+1));
                memset(t->pcName,0x00,sizeof(char)*(strlen(keyName)+1));
                strcpy(t->pcName,keyName);

t->pcValue=(char *)malloc(sizeof(char)*(strlen(keyValue)+1));
                memset(t->pcValue,0x00,sizeof(char)*(strlen(keyValue)+1));
                strcpy(t->pcValue,keyValue);

                t->pcComment=NULL;

t->next=ptr->next;
ptr->next=t;

                return 0;
        }
}

/* -------------------------------------------------------------------------*/ 
int deleteKey(const linelink head,const char *secName,const char *keyName)
{
        assert(((head!=NULL)&&(secName!=NULL))&&(keyName!=NULL));

        linelink ptr=locateSection(head,secName);
        if(ptr==NULL)
                return -1;
        else
        {
                linelink t=ptr->next;
while((t!=NULL)&&(t->nType!=1))
{
if((t->nType==2)&&(strcmp(t->pcName,keyName)==0))
{
ptr->next=t->next;

if(t->pcName!=NULL) free(t->pcName);
if(t->pcValue!=NULL) free(t->pcValue);
if(t->pcComment!=NULL) free(t->pcComment);
free(t);

return 0;
}
else
{
ptr=t;
t=ptr->next;
}
}

                return -1;
        }
}


/*
*Copyright (C) 2004.9, Jason.zhao
*All rights reserved.
*
*Name: analyse.h
*Version: 1.1
*Date: 2004/9/9
*/

#ifndef STR_ANALYSE_H
#define STR_ANALYSE_H

#include
#include
#include

#define COMMENT_FLAG   0x23   /* .config/.ini file comment symbol # */

#define SECTION_START_FLAG   0x5B
#define SECTION_END_FLAG   0x5D   /* .config/.ini file section symbol []*/

#define KEY_FLAG  0x3D   /* .config/.ini file key symbol =     */

int strAnalyse(char *pcName,char *pcValue,char *pcComment,const char *pcSource,int maxlength);

#endif
 
 
/*analyse.c*/
#include "analyse.h"

/* ------------------------------------------------------------------------- */
int  strTrimSpace(char *pcResult,const char *pcSource,int maxlength)
{
assert(pcResult!=NULL);
assert((pcSource!=NULL)&&(strlen(pcSource)<=maxlength));

/*delete the head space&TAB */
int i=0;
while(((32==pcSource[i])||(9==pcSource[i]))&&(ii++;

/*delete the tail space&TAB */
int j=strlen(pcSource)-1;
while(((32==pcSource[j])||(9==pcSource[j]))&&(j>=0))
j--;

/*save result*/
int k=0;
for(k=0;k<=j-i;k++)
pcResult[k]=pcSource[i+k];
pcResult[k]='\0';

return 0;
}

/* ------------------------------------------------------------------------- */
int strSplitComment(char *pcNComment,char *pcComment,const char *pcSource,int maxlength)
{
assert((pcNComment!=NULL)&&(pcComment!=NULL));
        assert((pcSource!=NULL)&&(strlen(pcSource)<=maxlength));

/*locate the index of COMMENT_FLAG*/
int i=0;
while((COMMENT_FLAG!=pcSource[i])&&(ii++;

/*save result*/
int j=0;
for(j=0;jpcNComment[j]=pcSource[j];
pcNComment[j]='\0';

for(j=i+1;j                pcComment[j-i-1]=pcSource[j];
        pcComment[j-i-1]='\0';

char temp[maxlength+1];
memset(temp,0x00,maxlength+1);

strcpy(temp,pcNComment);
strTrimSpace(pcNComment,temp,maxlength);

strcpy(temp,pcComment);
        strTrimSpace(pcComment,temp,maxlength);

return 0;
}

/* ------------------------------------------------------------------------- 
*return value:
*0 success,pcResult -> section name
*-1 not section
*/
int strGetSection(char *pcResult,const char *pcSource,int maxlength)
{
assert(pcResult!=NULL);
        assert((pcSource!=NULL)&&(strlen(pcSource)<=maxlength));

if(strlen(pcSource)>2)
{
if((SECTION_START_FLAG==pcSource[0])&&(SECTION_END_FLAG==pcSource[strlen(pcSource)-1]))
          {
                 int i;
for(i=0;i                         pcResult[i]=pcSource[i+1];
                        pcResult[i]='\0';

char temp[maxlength+1];
         memset(temp, 0x00, maxlength+1);

strcpy(temp,pcResult);
strTrimSpace(pcResult,temp,maxlength);

if(pcResult[0]!='\0')
return 0;
}
}

return -1;
}

/* ------------------------------------------------------------------------- */
int strGetKeyAndValue(char *pcKey,char *pcValue,const char *pcSource,int maxlength)
{
        assert(pcValue!=NULL);
assert(pcKey!=NULL);
        assert((pcSource!=NULL)&&(strlen(pcSource)<=maxlength));

char temp[maxlength+1];
        memset(temp, 0x00, maxlength+1);

char keyTemp[maxlength+1];
char valueTemp[maxlength+1];

memset(keyTemp, 0x00, maxlength+1);
memset(valueTemp, 0x00, maxlength+1);

        /*locate the index of KEY_FLAG*/
int i=0;
while((KEY_FLAG!=pcSource[i])&&(ii++;

/*get key name*/
int j=0;
for(j=0;jkeyTemp[j]=pcSource[j];
keyTemp[j]='\0';

        strcpy(temp,keyTemp);
        strTrimSpace(keyTemp,temp,maxlength);

if(keyTemp[0]=='\0')
                return -1;

/*get key value*/
for(j=i+1;j         valueTemp[j-i-1]=pcSource[j];
        valueTemp[j-i-1]='\0';

strcpy(temp,valueTemp);
        strTrimSpace(valueTemp,temp,maxlength);

if(valueTemp[0]=='\0')
return -1;

/*save result*/
strcpy(pcKey,keyTemp);
strcpy(pcValue,valueTemp);

return 0;
}

/* ------------------------------------------------------------------------- 
*return value:
*1   section ;pcName -> section name,pcComment -> comment
*2   key ;pcName -> key name ,pcValue -> key value,pcComment -> comment
*3   comment ;pcComment -> comment 
*-1  other
*/
int strAnalyse(char *pcName,char *pcValue,char *pcComment,const char *pcSource,int maxlength)
{
assert(((pcName!=NULL)&&(pcValue!=NULL))&&(pcComment!=NULL));
        assert((pcSource!=NULL)&&(strlen(pcSource)<=maxlength));

char temp[maxlength+1];
memset(temp,0x00,maxlength+1);

/* COMMENT is prior to SECTION,KEY*/
strSplitComment(temp,pcComment,pcSource,maxlength);

if(temp[0]=='\0')
{
if(pcComment[0]!='\0') return 3;
else return -1;
}
/*SECTION is prior to KEY*/
else if(strGetSection(pcName,temp,maxlength)==0)
return 1;
/*KEY is prior to others*/
else if((strGetKeyAndValue(pcName,pcValue,temp,maxlength))==0)
return 2;

return -1;
}

#ifndef tini_h
#define tini_h

#ifndef tmemlist_h
#include
#endif

typedef struct
{
  char * Name;
  char * Value;
  char * Comment;
}IniItemStru;


class TIniSet
{
private:
public:
  TMemList * mList;
  char * mName;
  char * mComment;
private:
  void FreeItem(IniItemStru * obj);
public:
  TIniSet();
  ~TIniSet();

  void SetInfo(char * setname,char * comment);

  int GoHead();
  int HaveNext();
  int Next();
  IniItemStru * GetItem();
  IniItemStru * GetItem(char * item);
  char * GetKey(char * item);
  int AddItem(char * item,char * key,char * comment);
  int SetKey(char * item,char * key);
  void RemoveKey(char * item,char * key);
  void RemoveItem(char * item);
};

class TIni
{
private:
  char mComment_Flag;
public:
  TMemList * mList;
private:
  int IniSeperate(char * line,char * name,char * value,char * comment);
public:
  TIni();
  ~TIni();
  void SetComment(char );
  TIniSet * GetSet(char * grpname);
  TIniSet * AddSet(char * grpname,char * comment);
  int RemoveSet(char * grpname);
  int AddItem(char * grpname,char * item,char * key,char * comment);
  int SetKey(char * grpname,char * item,char * key);
  void RemoveKey(char * grpname,char * item,char * key);
  void RemoveItem(char * grpname,char * item);
  IniItemStru * GetItem(char * grpname,char * item);
  char * GetKey(char * grpname,char * item);
  int GetItemKey(char * grpname,char * item,char * pkeyval);
  char * GetKey(char * ininame,char * grpname,char * item);
  int GetItemKey(char * ininame,char * grpname,char * item,char * pkeyval);
  int SaveToFile(char * filename);
  int LoadFile(char * filename);
};

#endif


/***************************************************************
* 模块名称:cini.cpp
* 功能描述:配置文件操作类
* 关键算法:
* 可移植性: unix / window / c++
* 外部引用:cini.h
* 作    者: mengwg
* 完工日期: 2001-02-25
* 最后修改日期: 2001-02-25
* 修改记录:
*   修改者:
*   修改描述:
*   修改日期:
*
*   修改者:
*   修改描述:
*   修改日期:
***************************************************************/

#include
#include
#include
#include
#include
#include
#include

/*******************************************************************
*                    下面是TIniSet类的成员函数
*******************************************************************/
/*
函数功能:释放一个节点
传入参数:
  obj: 要释放的节点
返回参数:
*/
void TIniSet::FreeItem(IniItemStru * obj)
{
  if(obj==NULL) return;
  if(obj->Name!=NULL) IMem.Free(obj->Name);
  if(obj->Value!=NULL) IMem.Free(obj->Value);
  if(obj->Comment!=NULL) IMem.Free(obj->Comment);
  IMem.Free(obj);
}

/*
函数功能:初始化
传入参数:
返回参数:
*/
TIniSet::TIniSet()
{
  mName = NULL;
  mComment = NULL;
  mList = new TMemList();
}

/*
函数功能:释放内存
传入参数:
返回参数:
*/
TIniSet::~TIniSet()
{
IniItemStru * obj;

  if(mName != NULL) IMem.Free(mName);
  if(mComment != NULL) IMem.Free(mComment);
  while(mList->GoHead())
  {
    obj = (IniItemStru * )mList->GetPtr();
    mList->Remove(obj);
    FreeItem(obj);
  };
  delete mList;
}

/*
函数功能:设置集合的名称和注释
传入参数:
  setname: 集合名称
  comment: 集合注释
返回参数:
*/
void TIniSet::SetInfo(char * setname,char * comment)
{
  if(mName != NULL)
  {
    IMem.Free(mName);
    mName=NULL;
  };
  if(mComment != NULL)
  {
    IMem.Free(mComment);
    mComment=NULL;
  };
  if(setname!=NULL)
  {
    mName = (char *)IMem.Malloc((int)strlen(setname)+1);
    strcpy(mName,setname);
  };
  if(comment!=NULL)
  {
    mComment = (char *)IMem.Malloc((int)strlen(comment)+1);
    strcpy(mComment,comment);
  };
}

/*
函数功能:到集合头
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TIniSet::GoHead()
{
  return mList->GoHead();
}

/*
函数功能:判断集合是否有下一条目
传入参数:
返回参数:
  有 1
  无 0
*/
int TIniSet::HaveNext()
{
  return mList->HaveNext();
}

/*
函数功能:定位到集合的下一条目
传入参数:
返回参数:
  有 1
  无 0
*/
int TIniSet::Next()
{
  return mList->Next();
}

/*
函数功能:取集合的当前条目
传入参数:
返回参数:
  成功 返回条目
  失败 返回NULL
*/
IniItemStru * TIniSet::GetItem()
{
  return (IniItemStru * )mList->GetPtr();
}

/*
函数功能:根据名称取一个条目
传入参数:
  item: 条目名称
返回参数:
  成功:节点指针
  失败:NULL
*/
IniItemStru * TIniSet::GetItem(char * item)
{
IniItemStru * obj;

  if(item==NULL) return NULL;
  mList->GoHead();
  while(1)
  {
    obj = (IniItemStru * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->Name==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    if(!strcmp(obj->Name,item))
      return obj;
    if(!mList->Next()) break;
  };
  return NULL;
}

/*
函数功能:根据名称取一个条目的值
传入参数:
  item: 条目名称
返回参数:
  成功:条目的值
  失败:NULL
*/
char * TIniSet::GetKey(char * item)
{
IniItemStru * obj;

  if(item==NULL) return NULL;
  mList->GoHead();
  while(1)
  {
    obj = (IniItemStru * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->Name==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    //printf("objname %s item %s\n",obj->Name,item);
    if(!strcmp(obj->Name,item))
      return obj->Value;
    if(!mList->Next()) break;
  };
  return NULL;
}

/*
函数功能:在集合里添加一个条目
传入参数:
  item: 条目名称
  key: 条目的值
  comment: 条目的注释
返回参数:
  成功 1
  失败 0
*/
int TIniSet::AddItem(char * item,char * key,char * comment)
{
IniItemStru * obj;

  obj=(IniItemStru * )IMem.Malloc(sizeof(IniItemStru));
  if(obj==NULL) goto malloc_err;
  obj->Name=obj->Value=obj->Comment=NULL;

  if(item!=NULL)
  {
    obj->Name=(char *)IMem.Malloc((int)strlen(item)+1);
    if(obj->Name==NULL) goto malloc_err;
    strcpy(obj->Name,item);
  };
  if(key!=NULL)
  {
    obj->Value=(char *)IMem.Malloc((int)strlen(key)+1);
    if(obj->Value==NULL) goto malloc_err;
   strcpy(obj->Value,key);
  };
  if(comment!=NULL)
  {
    obj->Comment=(char *)IMem.Malloc((int)strlen(comment)+1);
    if(obj->Comment==NULL) goto malloc_err;
    strcpy(obj->Comment,comment);
  };
  if(mList->AddTail(obj))
    return 1;
malloc_err:
  FreeItem(obj);
  return 0;
}

/*
函数功能:设置一个条目的值
传入参数:
  item: 条目名称
  key: 条目的值
返回参数:
  成功 1
  失败 0
*/
int TIniSet::SetKey(char * item,char * key)
{
IniItemStru * obj;

  if(item==NULL) return 0;
  mList->GoHead();
  while(1)
  {
    obj = (IniItemStru * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->Name==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    if(strcmp(obj->Name,item))
    {
      if(!mList->Next()) break;
      continue;
    };
    if(obj->Value==NULL)
    {
      IMem.Free(obj->Value);
      obj->Value=NULL;
    };
    if(key!=NULL)
    {
      obj->Value=(char *)IMem.Malloc((int)strlen(key)+1);
      strcpy(obj->Value,key);
      return 1;
    };
    if(!mList->Next()) break;
  };
  AddItem(item,key,NULL);
  return 1;
}

/*
函数功能:根据值删除一个条目
传入参数:
  item: 条目名称
  key: 条目的值
返回参数:
*/
void TIniSet::RemoveKey(char * item,char * key)
{
IniItemStru * obj;

  if(item==NULL||key==NULL) return;
  mList->GoHead();
  while(1)
  {
    obj = (IniItemStru * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->Name==NULL||obj->Value==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    if(!strcmp(obj->Name,item)&&!strcmp(obj->Value,key))
    {
      mList->Remove(obj);
      FreeItem(obj);
      continue;
    };
    if(!mList->Next()) break;
  };
}

/*
函数功能:根据名称删除一个条目
传入参数:
  item: 条目名称
返回参数:
*/
void TIniSet::RemoveItem(char * item)
{
IniItemStru * obj;

  if(item==NULL) return;
  mList->GoHead();
  while(1)
  {
    obj = (IniItemStru * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->Name==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    if(!strcmp(obj->Name,item))
    {
      mList->Remove(obj);
      FreeItem(obj);
      continue;
    };
    if(!mList->Next()) break;
  };
}


/*******************************************************************
*                    下面是TIni类的成员函数
*******************************************************************/

/*
函数功能:初始化
传入参数:
返回参数:
*/
TIni::TIni()
{
  mComment_Flag = ';';
  mList = new TMemList();
}

/*
函数功能:释放内存
传入参数:
返回参数:
*/
TIni::~TIni()
{
TIniSet * obj;

  while(mList->GoHead())
  {
    obj = (TIniSet * )mList->GetPtr();
    mList->Remove(obj);
    delete obj;
  };
  delete mList;
}

/*
函数功能:设置标识注释的字符
传入参数:
  flag: 标识注释的字符
返回参数:
*/
void TIni::SetComment(char flag)
{
  mComment_Flag = flag;
}

/*
函数功能:根据名称取一个集合指针
传入参数:
  grpname: 集合名称
返回参数:
  成功:集合指针
  失败:NULL
*/
TIniSet * TIni::GetSet(char * grpname)
{
TIniSet * obj;

  if(grpname==NULL) return NULL;
  mList->GoHead();
  while(1)
  {
    obj = (TIniSet * )mList->GetPtr();
    if(obj==NULL) break;
    if(obj->mName==NULL)
    {
      if(!mList->Next()) break;
      continue;
    };
    if(!strcmp(obj->mName,grpname))
      return obj;
    if(!mList->Next()) break;
  };
  //printf("unable to get set %s\n",grpname);
  return NULL;
}

/*
函数功能:添加一个集合
传入参数:
  grpname: 集合名称
  comment: 集合注释
返回参数:
  成功:集合指针
  失败:NULL
*/
TIniSet * TIni::AddSet(char * grpname,char * comment)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj!=NULL)
  {
    obj->SetInfo(grpname,comment);
    return obj;
  };
  obj=new TIniSet();
  obj->SetInfo(grpname,comment);
  if(!mList->AddTail(obj))
  {
    delete obj;
    return NULL;
  };
  return obj;
}

/*
函数功能:根据集合名称删除一个集合
传入参数:
  grpname: 集合名称
返回参数:
  成功:1
  失败:0
*/
int TIni::RemoveSet(char * grpname)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return 0;
  mList->Remove(obj);
  delete obj;
  return 1;
}

/*
函数功能:在集合里添加一个条目
传入参数:
  grpname: 集合名称
  item: 条目名称
  key: 条目的值
  comment: 条目的注释
返回参数:
  成功 1
  失败 0
*/
int TIni::AddItem(char * grpname,char * item,char * key,char * comment)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return 0;
  return obj->AddItem(item,key,comment);
}

/*
函数功能:设置一个条目的值
传入参数:
  grpname: 集合名称
  item: 条目名称
  key: 条目的值
返回参数:
  成功 1
  失败 0
*/
int TIni::SetKey(char * grpname,char * item,char * key)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return 0;
  return obj->SetKey(item,key);
}

/*
函数功能:根据值删除一个条目
传入参数:
  grpname: 集合名称
  item: 条目名称
  key: 条目的值
返回参数:
*/
void TIni::RemoveKey(char * grpname,char * item,char * key)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return;
  obj->RemoveKey(item,key);
}

/*
函数功能:根据名称删除一个条目
传入参数:
  grpname: 集合名称
  item: 条目名称
返回参数:
*/
void TIni::RemoveItem(char * grpname,char * item)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return;
  obj->RemoveItem(item);
}

/*
函数功能:根据名称取一个条目
传入参数:
  grpname: 集合名称
  item: 条目名称
返回参数:
  成功:节点指针
  失败:NULL
*/
IniItemStru * TIni::GetItem(char * grpname,char * item)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL) return NULL;
  return obj->GetItem(item);
}

/*
函数功能:根据名称取一个条目的值
传入参数:
  grpname: 集合名称
  item: 条目名称
返回参数:
  成功:条目的值
  失败:NULL
*/
char * TIni::GetKey(char * grpname,char * item)
{
TIniSet * obj;

  obj=GetSet(grpname);
  if(obj==NULL)
  {
    printf("unable to get set %s\n",grpname);
    return NULL;
  };
  return obj->GetKey(item);
}

/*
函数功能:根据名称取一个条目的值
传入参数:
  grpname: 集合名称
  item: 条目名称
  pkeyval: 用于存放条目值的内存指针
返回参数:
  成功:1,同时把条目的值存放在pkeyval的内存中
  失败:0
*/
int TIni::GetItemKey(char * grpname,char * item,char * pkeyval)
{
char * p;
  p=GetKey(grpname,item);
  if(p==NULL) return 0;
  strcpy(pkeyval,p);
  return 1;
};

/*
函数功能:根据名称取一个条目的值
传入参数:
  ininame: ini文件名称
  grpname: 集合名称
  item: 条目名称
返回参数:
  成功:条目的值
  失败:NULL
*/
char * TIni::GetKey(char * ininame,char * grpname,char * item)
{
TIni ini;
static char itemvalue[500];
char * pos;

  itemvalue[0]=0;
  if(!ini.LoadFile(ininame))
    return itemvalue;
  pos = ini.GetKey(grpname,item);
  if(pos==NULL) return itemvalue;
  strcpy(itemvalue,pos);
  return itemvalue;
}

/*
函数功能:根据名称取一个条目的值
传入参数:
  ininame: ini文件名称
  grpname: 集合名称
  item: 条目名称
返回参数:
  成功:1,同时把条目的值存放在pkeyval的内存中
  失败:0
*/
int TIni::GetItemKey(char * ininame,char * grpname,char * item,char * pkeyval)
{
char * p;
  p=GetKey(ininame,grpname,item);
  if(p==NULL) return 0;
  strcpy(pkeyval,p);
  return 1;
};

/*
函数功能:解析一行配置信息
传入参数:
  line: 原始信息
  name: 名称
  value:值
  comment:注释
返回参数:
  定义的类型
  如果是集合定义就返回 1
  否则返回 0
*/
int TIni::IniSeperate(char * line,char * name,char * value,char * comment)
{
char * pos;
int isgrp=0;

  *name=*value=*comment=0;
  pos=line;
  while(*pos==' '||*pos==9) pos++;
  if(*pos=='[')
  {
    pos++;
    while(*pos==' '||*pos==9) pos++;
    while(*pos!=' '&&*pos!=9&&*pos!=']'&&*pos!=0)
      *name++=(char)tolower(*pos++);
    *name=0;
    while(*pos==' '||*pos==9||*pos==']') pos++;
    isgrp = 1;
  }
  else
  {
    while(*pos!='='&&*pos!=mComment_Flag&&*pos!=0&&*pos!=' '&&*pos!=9)
      *name++=(char)tolower(*pos++);
    *name=0;
  };
  while(*pos==' '||*pos==9||*pos=='=') pos++;
  while(*pos!=mComment_Flag&&*pos!=0)
    *value++=*pos++;
  *value=0;
  while(*pos==mComment_Flag) pos++;
  while(*pos!=0)
    *comment++=*pos++;
  *comment=0;
  return isgrp;
}


/*
函数功能:更新配置文件
传入参数:
  filename: 要保存的文件名
返回参数:
  0 保存失败
  1 保存成功
*/
int TIni::SaveToFile(char * filename)
{
FILE * fp;
TIniSet * grp;
IniItemStru * item;

  fp=fopen(filename,"wt");
if(fp==(FILE *) NULL)
    return 0;
  mList->GoHead();
  while(1)
  {
    grp = (TIniSet * )mList->GetPtr();
    if(grp==NULL) break;
    if(grp->mName!=NULL)
      if(grp->mName[0]!=0)
        fprintf(fp,"[%s]",grp->mName);
    if(grp->mComment!=NULL)
    {
      if(grp->mComment[0]!=0)
        fprintf(fp,"     ;%s",grp->mComment);
    };
    if(grp->mName!=NULL||grp->mComment!=NULL)
      fprintf(fp,"\n");
    grp->GoHead();
    while(1)
    {
      item=grp->GetItem();
      if(item==NULL)
        break;
      if(item->Name!=NULL)
        if(item->Name[0]!=0)
          fprintf(fp,"%s ",item->Name);
      if(item->Value!=NULL)
        if(item->Value[0]!=0)
          fprintf(fp,"= %s",item->Value);
        else
          fprintf(fp,"= ");
      if(item->Comment!=NULL)
        if(item->Comment[0]!=0)
          fprintf(fp,"     ;%s",item->Comment);
      fprintf(fp,"\n");
      if(!grp->Next()) break;
    };
    fprintf(fp,"\n");
    if(!mList->Next()) break;
  };
   fclose(fp);
   return 1;
}

/*
函数功能:打开配置文件
传入参数:
  filename: 要打开的文件名
返回参数:
  成功: 1
  失败: 0
*/
int TIni::LoadFile(char * filename, )
{
FILE    * fp;
TIniSet * grp;
int  isgrp,len;
char line[1024]={0,0,0},name[1024],value[1024],comment[1024];

//在提取之前应该先清除一下,mengwg 2001-08-20 modi
TIniSet * obj;

  while(mList->GoHead())
  {
    obj = (TIniSet * )mList->GetPtr();
    mList->Remove(obj);
    delete obj;
  };
fp=fopen(filename,"rt");
if(fp==(FILE *) NULL)
return 0;

while(fgets(line,1024,fp)!=NULL)
{
    IString.Allt(line);
    len=(int)strlen(line);
    while(len>0)
      if(line[len-1]==0x0a||line[len-1]==0x0d)
        len--;
      else
        break;
    line[len]=0;
    if(len==0)
      continue;
    isgrp=IniSeperate(line,name,value,comment);
    len=(int)strlen(value);
    while(len>0)
      if(value[len-1]==' ')
        len--;
      else
        break;
    value[len]=0;
    if(isgrp)
    {
      grp = AddSet(name,comment);
      if(grp==NULL)
        goto load_err;
      continue;
    };
    if(grp==NULL)
    {
      grp = AddSet(NULL,NULL);
      if(grp==NULL)
        goto load_err;
    };
    grp->AddItem(name,value,comment);
}
fclose(fp);
return 1;
load_err:
  fclose(fp);
  return 0;
}

#ifdef TIni_Test
#include
int main()
{
TIni ini;

  ini.LoadFile("test.ini");
  ini.RemoveSet("general");
  printf("key of mintermid is '%s'\n",ini.GetKey("general","mintermid"));
  printf("key of serialno is '%s'\n",ini.GetKey("general","serialno"));
  //ini.RemoveItem("general","serialno");
  //ini.RemoveSet("general");
  ini.SaveToFile("save.ini");
  getchar();
  return 1;
}
#endif

#ifndef tmemlist_h
#define tmemlist_h

struct MemStru
{
  void * Ptr;
  struct MemStru * Next,* Last;
};

class TMemList
{
protected:
  struct MemStru * mHead,* mTail, * mCur;
  void * mAssistantPtr;
  int mCount;

protected:
  struct MemStru * _GetNode(void * ptr);
  int _AddBeforeNode(struct MemStru * ptr,void * toadd);
  int _AddAfterNode(struct MemStru * ptr,void * toadd);
  int _RemoveNode(struct MemStru * ptr);
  int (* _Find_Handle)(void * ptr,void * assist_ptr);

public:
  TMemList();
  ~TMemList();

  int GetCount();
  int GoHead();
  int GoTail();
  int IsEmpty();
  int HaveNext();
  int Next();
  int HaveLast();
  int Last();

  void * GetPtr();
  void * GetPtr(int pos);
  void * GetLast();
  void * GetNext();
  void * GetHead();
  void * GetTail();

  int RemoveHead();
  int RemoveTail();
  int RemoveAll();
  int FreeAllContent();
  int Remove(void * ptr);

  int AddHead(void * toadd);
  int AddTail(void * toadd);
  int AddAfter(void * ptr,void * toadd);
  int AddBefore(void * ptr,void * toadd);

  void * Find(int (* find_handle)(void * ptr,void * ass_ptr),void *assistantptr);
  void * FindNext();

  int Sort(int (* sort_handle)(void * ,void * ));
};
#endif

[/code:1:71d5d16aa5]

memlist.h 的内容如上,TMemList是一个链表的实现,vc里面有类似的实现。
system.h 主要是一些平台的定义,没什么关系。
[code:1:71d5d16aa5]
#ifndef system_h
#define system_h

/*
定义操作系统
#define WINDOW_SYS
#define UNIX_SYS
#define AIX_SYS
#define SCOUNIX_SYS
#define SOLARIS_SYS
#define HP_SYS
#define LINUX_SYS
#define DIGITAL_SYS
*/
#define WINDOW_SYS

/*
由于LINUX上编译基本上和SOLARIS上一样,故做下面定义,但在asyncapi中有特殊处理
*/
#ifdef LINUX_SYS
#define SOLARIS_SYS
#endif

/*
定义语言
#define VISUALC_LANG
#define CBUILDER3_LANG
*/
//#define CBUILDER3_LANG
//#define VISUALC_LANG

/*
定义数据库
#define BDE_DBMS
#define ORACLE_DBMS
#define NETDB_DBMS
#define INFORMIX_DBMS
#define SYBASE_DBMS
*/
#define BDE_DBMS
/* 是否自动调用构造函数 */
#define CLASS_AUTOFREE
/*
定义中间件
#define LINKTUXEDO_LIB
#define OTHERMIDWARE_LIB
#define OTHERMIDWARE_LIB
#define LINKTONG_LIB
#define OTHERMIDWARE_LIB
#define LINKTONG_LIB
#define OTHERMIDWARE_LIB
#define LINKTONG_LIB
*/

#ifdef  WINDOW_SYS
/* 在WINDOW平台上不支持 thread_t类型 */
#define thread_t        int
#endif

#ifdef  UNIX_SYS
/* 在UNIX上关闭网络连接函数为close,在WINDOW平台上为closesocket
   要求程序中一律采用closesocket
*/
#define closesocket     close
#endif

#ifdef  SCOUNIX_SYS
/* SCO目前不支持线程编程 */
/*
#define thread_t        int
#define pthread_mutex_t int
*/
/* 用于网络编程时的计算 */
#define NOFILE          32
#endif

#ifdef HP_SYS
#define thread_t        pthread_t
#define thr_self        pthread_self
#endif

#ifdef  AIX_SYS
/* 在AIX上一律采用 pthread方式 */
#define thread_t        pthread_t
#define thr_self        pthread_self
#endif

#ifdef  LINUX_SYS
#define thread_t        pthread_t
#define thr_self        pthread_self
#endif

#ifdef UNIX_SYS
#define ITF_Ini         "../etc/itf.ini"
#define USysInfo_Ini    "../etc/usysinfo.ini"
#else
#define ITF_Ini         "..\\etc\\itf.ini"
#define USysInfo_Ini    "..\\etc\\usysinfo.ini"
#endif

#ifdef WINDOW_SYS
typedef  __int64 long64;
#endif

#ifdef UNIX_SYS
typedef long long long64;
#endif

void m_sleep(int num);
void m_usleep(int num);

#endif

[/code:1:71d5d16aa5][/code]

 

--------------------------------------------------------------------------------
 yanrili 回复于:2004-10-27 11:50:33
mengwg:
    能否提供你这个程序的完整代码,你打出来的这些好像还不完整吧,我试了还不能用。
    我最新的一个程序需要读写ini文件,想参考一下你的程序。谢谢!

 

--------------------------------------------------------------------------------
 yanrili 回复于:2004-10-27 12:43:43
还少个memlist.c 吧,
我在linux下用gcc编译,还不行。
mengwg老大,能把你这个程序补充完整吗?

 

--------------------------------------------------------------------------------
 robinliu76 回复于:2004-11-05 13:15:19
[quote:d427ceddc6]int S4GetProfileData(const char * ps_AppName,const char * ps_KeyName,const char * ps_DefaultString,
                     char * ps_ResultString,const char * ps_FileName,char * ps_ErrMsg)
{
   int li_Count,li_KeyNameLen=0;
   char ls_Buffer[1024];
   char ls_AppName[52];
   char ls_KeyName[50];
   char ls_KeyValue[256];
   char lc_AppFlag='0',lc_KeyFlag='0';
   FILE *lpf_CfgFile;
   sprintf(ls_AppName,"[%s]",ps_AppName);
   
   if((lpf_CfgFile=fopen(ps_FileName,"r"))==NULL)
   {
      strcpy(ps_ErrMsg,ErrMsg[0]);
      return S4ERROR;
   }
   
   while(!feof(lpf_CfgFile))
   {
      strcpy(ls_Buffer,"");
      fgets(ls_Buffer,1024,lpf_CfgFile);
      if((ls_Buffer[strlen(ls_Buffer)-1]==0x0a)||(ls_Buffer[strlen(ls_Buffer)-1]==0x0d)) 
         ls_Buffer[strlen(ls_Buffer)-1]='\0';
      S4DelChar(ls_Buffer,' ',0);
      if(ls_Buffer[0]==';') continue;
      if(strstr(ls_Buffer,ls_AppName))
      {
         lc_AppFlag='1';
         continue;
      }
      if(strstr(ls_Buffer,ps_KeyName))
      {
        for(li_Count=0;li_Count           if(ls_Buffer[li_Count]=='=') {li_KeyNameLen=li_Count;break;}
        if(li_KeyNameLen==0)
        {
         if(strcmp(ls_Buffer,ps_KeyName)==0)
         {
              strcpy(ps_ErrMsg,ErrMsg[1]);
               return S4PROFILE_ERROR_KEYNOTDEFINE;
            }
            else continue;
        }
        memset(ls_KeyName,0,50);
        memcpy(ls_KeyName,ls_Buffer,li_KeyNameLen);
        ls_KeyName[li_KeyNameLen]='\0';
        S4DelChar(ls_KeyName,' ',0);
        if(strcmp(ls_KeyName,ps_KeyName)!=0) continue;
        lc_KeyFlag='1';
         memset(ls_KeyValue,0,256);
         memcpy(ls_KeyValue,ls_Buffer+li_Count+1,256);
         ls_KeyValue[strlen(ls_KeyValue)]='\0';
         S4DelChar(ls_KeyValue,' ',0);
         if(strcmp(ls_KeyValue,"")==0)
         {
            strcpy(ps_ErrMsg,ErrMsg[1]);
            return S4PROFILE_ERROR_KEYNOTDEFINE;
         }
         strcpy(ps_ResultString,ls_KeyValue);
         fclose(lpf_CfgFile);
         return S4OK;
      }
      if((ls_Buffer[0]=='[')&&(lc_AppFlag=='1')) lc_AppFlag='2';
      if(lc_AppFlag=='2') break;
   }
   fclose(lpf_CfgFile);
   if(lc_AppFlag=='0')
   {
      strcpy(ps_ErrMsg,ErrMsg[2]);
      strcpy(ps_ResultString,ps_DefaultString);
      return S4PROFILE_ERROR_APPNOTFOUND;
   }
   if(lc_KeyFlag=='0'||lc_AppFlag=='2')
   {
      strcpy(ps_ErrMsg,ErrMsg[3]);
      strcpy(ps_ResultString,ps_DefaultString);
      return S4PROFILE_ERROR_KEYNOTFOUND;
   }
}

int S4PutProfileKey(const char * ps_AppName,const char * ps_KeyName,const char * ps_PutString,const char * ps_FileName,char * ps_ErrMsg)
{
   int li_Count;
   char ls_TempCfgFile[256];
   char ls_AppName[52];
   char ls_KeyName[50];
   char ls_Buffer[1024];
   char li_KeyNameLen;
   char lc_AppFlag='0';
   FILE *lpf_CfgFile,*lpf_TempCfgFile;
   
   sprintf(ls_AppName,"[%s]",ps_AppName);
   sprintf(ls_TempCfgFile,"%s.tmp",ps_FileName);
   if(rename(ps_FileName,ls_TempCfgFile)<0)
   {
      strcpy(ps_ErrMsg,ErrMsg[4]);
      return S4ERROR;
   }
   
   if((lpf_TempCfgFile=fopen(ls_TempCfgFile,"r+"))==NULL)
   {
      strcpy(ps_ErrMsg,ErrMsg[0]);
      return S4ERROR;
   }
   if((lpf_CfgFile=fopen(ps_FileName,"w"))==NULL)
   {
      strcpy(ps_ErrMsg,ErrMsg[0]);
      return S4ERROR;
   }
   
   while(!feof(lpf_TempCfgFile))
   {
      strcpy(ls_Buffer,"");
      fgets(ls_Buffer,1024,lpf_TempCfgFile);
      if(ls_Buffer[0]==';') 
      {
         fputs(ls_Buffer,lpf_CfgFile);
         continue;
      }
      if(strstr(ls_Buffer,ls_AppName)&&(lc_AppFlag=='0')) 
      {
         fputs(ls_Buffer,lpf_CfgFile);
         fprintf(lpf_CfgFile,"%s=%s\n",ps_KeyName,ps_PutString);
         lc_AppFlag='1';
         continue;
      }
      if(strstr(ls_Buffer,ps_KeyName))
      {
         for(li_Count=0;li_Count           if(ls_Buffer[li_Count]=='=') {li_KeyNameLen=li_Count;break;}
        if(li_KeyNameLen==0)
        {
           if(strcmp(ls_Buffer,ps_KeyName)==0) continue;              
        }
        else
        {
           memset(ls_KeyName,0,50);
           memcpy(ls_KeyName,ls_Buffer,li_KeyNameLen);
           ls_KeyName[li_KeyNameLen]='\0';
           S4DelChar(ls_KeyName,' ',0);
           if(strcmp(ls_KeyName,ps_KeyName)==0) continue;
        }
      }
      fputs(ls_Buffer,lpf_CfgFile);
      if((ls_Buffer[0]=='[')&&(lc_AppFlag=='1')) lc_AppFlag='2';
   }
   if(lc_AppFlag=='0')
   {
      fprintf(lpf_CfgFile,"%s\n",ls_AppName);
      fprintf(lpf_CfgFile,"%s=%s\n",ps_KeyName,ps_PutString);
   }
   fclose(lpf_TempCfgFile);
   fflush(lpf_CfgFile);
   fclose(lpf_CfgFile);
   remove(ls_TempCfgFile);
   
   return S4OK;
}[/quote:d427ceddc6]

 

--------------------------------------------------------------------------------
 robinliu76 回复于:2004-11-05 13:18:53
:oops:

 

--------------------------------------------------------------------------------
 mengwg 回复于:2004-11-05 17:03:21
[quote:a846699bd2="yanrili"]还少个memlist.c 吧,
我在linux下用gcc编译,还不行。
mengwg老大,能把你这个程序补充完整吗?[/quote:a846699bd2]

[code:1:a846699bd2]
/***************************************************************
* 模块名称:memlist.cpp
* 功能描述:内存列表管理类
* 关键算法:
* 可移植性: unix / window / c++
* 外部引用:memlist.h
* 作    者: 孟文光
* 完工日期: 2001-02-24
* 最后修改日期: 2001-02-24
* 修改记录:
*   修改者:
*   修改描述:
*   修改日期:
***************************************************************/
#include
#include
#include
#include
#include

/*
函数功能:初始化
传入参数:
返回参数:
*/
TMemList::TMemList()
{
  mHead = NULL;
  mTail = NULL;
  mCur = NULL;
  _Find_Handle = NULL;
  mCount = 0;
}

/*
函数功能:构造函数,释放内存
传入参数:
返回参数:
*/
TMemList::~TMemList()
{
  RemoveAll();
}

/*
函数功能:取记录数
传入参数:
返回参数:
  记录数
*/
int TMemList::GetCount()
{
  return mCount;
}

/*
函数功能:在指定节点前面添加一个节点
传入参数:
  ptr:指定的节点
  toadd: 要添加的内存指针地址
返回参数:
  1 成功
  0 失败
*/
int TMemList::_AddBeforeNode(struct MemStru * ptr,void * toadd)
{
struct MemStru * obj;

  obj = (struct MemStru *)TMemSafe::Malloc(sizeof(struct MemStru));
  if(obj==NULL) return 0;
  obj->Next = NULL;
  obj->Last = NULL;
  obj->Ptr = toadd;
  mCount ++;
  if(mTail==NULL)
  {
    mTail = mHead = obj;
    mCur = mHead;
    return 1;
  };
  if(ptr==NULL)
    ptr = mTail;
  if(ptr->Last!=NULL)
    ptr->Last->Next=obj;
  obj->Last = ptr->Last;
  obj->Next = ptr;
  ptr->Last = obj;
  if(ptr==mHead)
    mHead = obj;
  return 1;
}

/*
函数功能:在指定节点后面添加一个节点
传入参数:
  ptr:指定的节点
  toadd: 要添加的内存指针地址
返回参数:
  1 成功
  0 失败
*/
int TMemList::_AddAfterNode(struct MemStru * ptr,void * toadd)
{
struct MemStru * obj;

  obj = (struct MemStru *)TMemSafe::Malloc(sizeof(struct MemStru));
  if(obj==NULL) return 0;
  obj->Next = NULL;
  obj->Last = NULL;
  obj->Ptr = toadd;
  mCount ++;
  if(mTail==NULL)
  {
    mTail = mHead = obj;
    mCur = mHead;
    return 1;
  };
  if(ptr==NULL)
    ptr = mTail;
  obj->Next = ptr->Next;
  if(ptr->Next!=NULL)
    ptr->Next->Last=obj;
  ptr->Next = obj;
  obj->Last = ptr;
  if(ptr==mTail)
    mTail = obj;
  return 1;
}

/*
函数功能:删除一个节点
传入参数:
  ptr:要删除的节点地址
返回参数:
  1 成功
  0 失败
*/
int TMemList::_RemoveNode(struct MemStru * ptr)
{
struct MemStru * last,* next;

  if(ptr==NULL) return 0;
  next = ptr->Next;
  last = ptr->Last;
  if(mHead==ptr)
    mHead = next;
  if(mTail==ptr)
    mTail = last;
  if(mCur==ptr)
  {
    if(next!=NULL)
      mCur = next;
    else
      mCur = last;
  };
  if(last!=NULL)
    last->Next = next;
  if(next!=NULL)
    next->Last = last;
  TMemSafe::Free(ptr);
  mCount --;
  return 1;
}

/*
函数功能:根据内存地址取节点地址
传入参数:
  ptr:指定的内存指针地址
返回参数:
  成功 返回节点地址
  失败 NULL
*/
struct MemStru * TMemList::_GetNode(void * ptr)
{
struct MemStru * obj;

  obj=mHead;
  while(obj!=NULL)
  {
    if(obj->Ptr==ptr) return obj;
    obj=obj->Next;
  };
  return NULL;
}


/*
函数功能:将当前指针定位到列表头
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::GoHead()
{
  if(mCount==0)
    return 0;
  mCur = mHead;
  if(mCur==NULL) return 0;
  return 1;
}

/*
函数功能:将当前指针定位到列表尾
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::GoTail()
{
  if(mCount==0)
    return 0;
  mCur = mTail;
  if(mCur==NULL) return 0;
  return 1;
}

/*
函数功能:判断指针列表是否为空
传入参数:
返回参数:
  为空 1
  非空 0
*/
int TMemList::IsEmpty()
{
  if(mCount==0)
    return 1;
  return 0;
}

/*
函数功能:能否将当前指针定位到下一个节点
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::HaveNext()
{
  if(mCount==0)
    return 0;
  if(mCur==mTail)
    return 0;
  return 1;
}

/*
函数功能:将当前指针定位到下一个节点
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::Next()
{
  if(mCount==0)
    return 0;
  if(mCur==mTail)
    return 0;
  mCur = mCur->Next;
  return 1;
}

/*
函数功能:能否将当前指针定位到上一个节点
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::HaveLast()
{
  if(mCount==0)
    return 0;
  if(mCur==mHead)
    return 0;
  return 1;
}

/*
函数功能:将当前指针定位到上一个节点
传入参数:
返回参数:
  成功 1
  失败 0
*/
int TMemList::Last()
{
  if(mCount==0)
    return 0;
  if(mCur==mHead)
    return 0;
  mCur = mCur->Last;
  return 1;
}

/*
函数功能:取得当前节点的内存指针
传入参数:
返回参数:
  成功 内存指针
  失败 NULL
*/
void * TMemList::GetPtr()
{
  if(mCount==0)
    return NULL;
  if(mCur!=NULL)
    return mCur->Ptr;
  return NULL;
}

/*
函数功能:取上一个指针地址
传入参数:
返回参数:
  成功 内存指针
  失败 NULL
*/
void * TMemList::GetLast()
{
  if(mCount==0)
    return NULL;
  if(mCur==mHead)
    return NULL;
  mCur = mCur->Last;
  return mCur->Ptr;
}

/*
函数功能:取下一个指针地址
传入参数:
返回参数:
  成功 内存指针
  失败 NULL
*/
void * TMemList::GetNext()
{
  if(mCount==0)
    return 0;
  if(mCur==mTail)
    return NULL;
  mCur = mCur->Next;
  return mCur->Ptr;
}


/*
函数功能:取得头节点的内存指针
传入参数:
返回参数:
  成功 内存指针
  失败 NULL
*/
void * TMemList::GetHead()
{
  if(mCount==0)
    return 0;
  if(mHead==NULL)
    return NULL;
  return mHead->Ptr;
}

/*
函数功能:取得尾节点的内存指针
传入参数:
返回参数:
  成功 内存指针
  失败 NULL
*/
void * TMemList::GetTail()
{
  if(mCount==0)
    return 0;
  if(mTail==NULL)
    return NULL;
  return mTail->Ptr;
}

/*
函数功能:删除指定的内存指针
传入参数:
  ptr:要删除的内存指针
返回参数:
  成功 1
  失败 0
*/
int TMemList::Remove(void * ptr)
{
struct MemStru * obj;

  obj = _GetNode(ptr);
  return _RemoveNode(obj);
}

/*
函数功能:在头上添加一个节点
传入参数:
  toadd: 要添加的内存指针地址
返回参数:
  成功 1
  失败 0
*/
int TMemList::AddHead(void * toadd)
{
  return _AddBeforeNode(mHead,toadd);
}

/*
函数功能:在末尾添加一个节点
传入参数:
  toadd: 要添加的内存指针地址
返回参数:
  成功 1
  失败 0
*/
int TMemList::AddTail(void * toadd)
{
  return _AddAfterNode(mTail,toadd);
}

/*
函数功能:在指定的内存后添加一个节点
传入参数:
  ptr:指定的内存指针
  toadd: 要添加的内存指针地址
返回参数:
  成功 1
  失败 0
*/
int TMemList::AddAfter(void * ptr,void * toadd)
{
struct MemStru * obj;

  obj = _GetNode(ptr);
  return _AddAfterNode(obj,toadd);
}

/*
函数功能:在指定的内存前添加一个节点
传入参数:
  ptr:指定的内存指针
  toadd: 要添加的内存指针地址
返回参数:
  成功 1
  失败 0
*/
int TMemList::AddBefore(void * ptr,void * toadd)
{
struct MemStru * obj;

  obj = _GetNode(ptr);
  return _AddBeforeNode(obj,toadd);
}

/*
函数功能:查找符合条件的内存指针
find_handle句柄的一个例子
int find_record(void * ptr,void * assistantptr)
{
int * iptr;
int * val;

  iptr = (int *) ptr;
  val = (int *) assistantptr;
  if(*iptr==*val)
    return 1;
  return 0;
}
传入参数:
  find_handle:用来查找的函数
  assistantptr:用于辅助查找的内存指针
返回参数:
  成功 找到的第一个指针
  失败 NULL
*/
void * TMemList::Find(int (* find_handle)(void * ,void *),void * assistantptr)
{
struct MemStru * next,* ptr;

  mAssistantPtr = assistantptr;
  _Find_Handle = find_handle;
  if(_Find_Handle==NULL) return NULL;
  ptr = mHead;
  while(ptr!=NULL)
  {
    if((_Find_Handle)(ptr->Ptr,mAssistantPtr))
    {
      mCur = ptr;
      return ptr->Ptr;
    };
    next = ptr->Next;
    ptr = next;
  };
  return NULL;
}

/*
函数功能:继续查找符合条件的内存指针
传入参数:
返回参数:
  成功 找到的下一个指针
  失败 NULL
*/
void * TMemList::FindNext()
{
struct MemStru * ptr;

  if(_Find_Handle==NULL) return NULL;
  ptr = mCur;
  if(ptr==mTail) return NULL;
  ptr=ptr->Next;
  while(ptr!=NULL)
  {
    if((_Find_Handle)(ptr->Ptr,mAssistantPtr))
    {
      mCur = ptr;
      return ptr->Ptr;
    };
    ptr = ptr->Next;
  };
  return NULL;
}

/*
函数功能:进行排序
sort_handle句柄的例子
对于字符型排序
int sort_record(void * src,void * tag)
{
char * ia,* ib;

  ia=(char *)(*(int *)src);
  ib=(char *)(*(int *)tag);
  return strcmp(ia,ib);
}

对于结构排序
struct Mcl;

int sort_record(void * src,void * tag)
{
struct Mcl * ia,* ib;

  ia=(struct Mcl *)(*(int *)src);
  ib=(struct Mcl *)(*(int *)tag);
  if(ia->mVal>ib->mVal) return 1;
  if(ia->mValmVal) return -1;
  return 0;
}

对于类排序
class TMcl;

int sort_record(void * src,void * tag)
{
TMcl * ia,* ib;

  ia=(TMcl *)(*(int *)src);
  ib=(TMcl *)(*(int *)tag);
  if(ia->mVal>ib->mVal) return 1;
  if(ia->mValmVal) return -1;
  return 0;
}

传入参数:
  sort_handle:用来排序的函数
返回参数:
  1 成功
  0 失败
*/
int TMemList::Sort(int (* sort_handle)(void * ,void * ))
{
int Ptr_Size= (int)sizeof(int *);
int  * buf;
int  * addr;
  if(num==0) return 1;
  buf=(int *)TMemSafe::Malloc(num*Ptr_Size);
  if(buf==NULL)
    return 0;
  ptr = mHead;
  addr = buf;
  while(ptr!=NULL)
  {
    *addr = (int)((char *)ptr->Ptr);
    ptr = ptr->Next;
    addr ++;
  };
#ifdef WINDOW_SYS
  qsort((char *) buf,num,Ptr_Size,
    (int (__cdecl *)(const void *,const void *) )sort_handle);
#endif

#if defined(SCOUNIX_SYS) || defined(HP_SYS) || defined(AIX_SYS) ||defined(SOLARIS_SYS)
  qsort((char *) buf,num,Ptr_Size,
    (int ( *)(const void *,const void *) )sort_handle);
#endif

//#if defined(SOLARIS_SYS)
//  qsort((char *) buf,num,Ptr_Size,
//    sort_handle);
//#endif

  ptr = mHead;
  addr = buf;
  while(ptr!=NULL)
  {
    ptr->Ptr = (void *)*addr;
    ptr = ptr->Next;
    addr ++;
  };
  GoHead();
  TMemSafe::Free(buf);
  return 1;
}

#ifdef TMemList_Test
#include
int sorta(void * a,void * b)
{
char * ia,* ib;

  ia=(char *)(*(int *)a);
  ib=(char *)(*(int *)b);
  return strcmp(ia,ib);
}

int testclist()
{
TMemList c;
char *list[]=
{"a5","sddssd4","21126","12349","3","5"};
int num=6,id;
char *ptr;

  printf("hello,world\n");
  for(id=0;id  {
    c.AddHead((void *)list[id]);
  };
  ptr=(char *)c.GetTail();
  printf("tail is %s count: %d\n",ptr,c.GetCount());
  c.Remove(list[2]);
  c.AddTail(list[2]);
  c.Sort(sorta);
  c.GoHead();
  while(1)
  {
    ptr=(char *)c.GetPtr();
    printf("%s\n",ptr);
    if(!c.Next()) break;
  };
  getchar();
  return 1;
}
#endif
[/code:1:a846699bd2]

 

--------------------------------------------------------------------------------
 bicycleor 回复于:2004-11-16 05:08:01
***********************************************
***********************************************

Example on how to use my code

***********************************************
***********************************************

/******************************************************
                Ini文件读写范例程序
                copyright (c) 2003 
                Written by Zhao, Shiliang
*******************************************************/
#include
#include

#include "IniFile.h"    //Include读写Ini文件的头文件

int main()
{
char aa[80];
        int i;
        printf("\n--------------------DEMO.C-------------------------\n");
        //首先需要打开将有读写的Ini文件
        i = OpenIniFile("/home/zhaosl/demo_win32.ini");
        if (!i) {
         //如果不确定该Ini文件是否为Unix类型文件,调用转换函数进行转换
            if (ToUnixStyle() != 0) printf("Fail to convert to unix style file.\n");
            
            //获取字符串类型的值
            i = GetIniString("test1", "ip", aa);
            if (!i) {
                printf("[test1]\tip = %s\n", aa);
            } else printf("[test1]_ip not found.\n");
            
            //获取整型、长整型、浮点数型的值
            printf("[test]\ti=%d\n", GetIniInteger("test", "i", -1));
            printf("[test]\tlong=%ld\n", GetIniLong("test", "long", -1));
            printf("[test]\tf=%g\n", GetIniDouble("test", "f", -1));
            
            /*写入整型、长整型、浮点数型的值
            SetIniInteger("test", "i", 0x1ffe);
            SetIniString("test", "i", "150000");
            SetIniLong("test", "i", 7500);
            SetIniDouble("test", "f", 75.876);
            */
            
            //获得文件中所有的段名,以提供的间隔符分开
            GetSections("#", aa);
            printf("Sections = %s\n", aa);
            
            //获得文件中指定段下所有的值("="后面的串值),以提供的间隔符分开
            GetSectionValues("test", "#", aa);
            printf("Section TEST has values: %s\n", aa);
            
            //读写文件后,关闭文件
            CloseIniFile();
            
        }
        printf("---------------------E N D-------------------------\n\n");
        return 0;
}


************************************************
************************************************
The C Code for reading Ini File on Unix/Linux/Window
************************************************
************************************************

/*************************************************************

       copywrite (c) Michael Zhao 2002 
       For Unix and Linux, but not limited to them.
       
[ History ]
        
2003-05-11  Zhao,Shi-liang Create the initial file 

2003-05-12  Zhao,Shi-liang
    (1) Support space in value, such as //[test] a=I am all right// returns 
        "I am all right" instead of "I"
    (2) Add "GetIniInteger", "GetIniLong", "GetIniDouble", "SetIniInteger", 
        "SetIniLong", "SetIniDouble"

2003-05-13  Zhao,Shi-liang 
    (1) Add "GetSectionValues", "GetSections"
    (2) Support Unix/Linux-style Ini File Only ( ending with '\n' )
    (3) Add "ToUnixStyle" to support Windows Ini Files (ending with '\r\n')

*************************************************************/
#ifndef __CINIFILE_H__
#define __CINIFILE_H__

#include
#include
#include
#include

#define MAX_BUFFER_SIZE        6000
#define MAX_VALUE_BUFFER_SIZE  128

char szBuffer[MAX_BUFFER_SIZE];
int  iBufferLen=0;
int  bBufferChanged=0;
FILE *fp=NULL;

//Declarations of Interfaces
int     OpenIniFile(const char *);
int     CloseIniFile(void);
int     ToUnixStyle(void);
int     GetIniString(const char *, const char *, char *);
int     SetIniString(const char *, const char *, const char *);

int     GetIniInteger(const char *, const char *, const int);
long    GetIniLong(const char *, const char *, const long);
double  GetIniDouble(const char *, const char *, const double);

int     SetIniInteger(const char *, const char *, const int);
int     SetIniLong(const char *, const char *, const long);
int     SetIniDouble(const char *, const char *, const double);

int     GetSectionValues(const char *, const char *, char *);
int     GetSections(const char *, char *);
// End of declaration of interfaces

/**********************************************
Name   : OpenIniFile
Input  :
       char *File_name : file to be open
Output :
        0 : File succefully opened
       -1 : Fail to open given file
       -2 : Fail to read buffer data
Process: Normal 
***********************************************/
int OpenIniFile(const char *pFile)
{
struct stat statbuf;
stat(pFile,&statbuf);
iBufferLen = 0; bBufferChanged = 0;
if ((fp=fopen(pFile, "r+")) == NULL) return -1;
if(fread(szBuffer,statbuf.st_size,1,fp) != 1) {
if (fp != NULL) fclose(fp);
fp = NULL;
return -2;
}
    iBufferLen = statbuf.st_size;
return 0;
}

/**********************************************
Name   : CloseIniFile
Input  : None
Output :
        0 : File succefully closed
       -1 : Fail to close already opened file
Process: Normal 
***********************************************/
int CloseIniFile(void)
{
if (fp != NULL) {
                if (bBufferChanged) {
                   rewind(fp);
                   fwrite(szBuffer, iBufferLen, 1, fp);
                }
if (!fclose(fp)) return 0;
else return -1;
} else return 0;
}

/**********************************************
Name   : ToUnixStyle
Input  : None
Output :
        0 : File succefully closed
       -1 : Fail to close already opened file
Process: Normal 
***********************************************/
int ToUnixStyle(void)
{
int i=0;
if (fp==NULL) return -1;
while (iif (szBuffer[i]=='\r') { szBuffer[i]=' '; bBufferChanged=1; }
i++;
}
return 0;
}

/**********************************************
Name   : GetIniString
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                char *pResult: Returned string
Output :
        0 : Identity Value successfully returned
       -1 : Fail to get the designated identity value
Process: Normal 
***********************************************/
int GetIniString(const char *pSection,const char *pIdent, char *pResult)
{
    int i=0;
    int j=0; 
    int min;
    int iKeyFound=-1;
    if (!strlen(pSection) || !strlen(pIdent) || (fp == NULL)) return -1;
    while (i        while ((i               ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
        if (i>=iBufferLen) return -1;
        if (szBuffer[i]=='#') { //ignore the lines beginning with '#'
            while ((i            if (i>=iBufferLen) return -1; 
            //Jump to the next line
            i++;
        } else {
            if (szBuffer[i]=='[') {
                i++;
                while ((i                       ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                if (i>=iBufferLen) return -1;
                if (strncmp(szBuffer+i, pSection, strlen(pSection))==0) { 
                    //Section may be found, let's see
                    i += strlen(pSection);
                    while ((i                           ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                    if (i>=iBufferLen) return -1;
                    if (szBuffer[i]==']') iKeyFound=0; i++;
                    //matched ] or not, ignore the line
                    while ((i                    if (i>=iBufferLen) return -1;
                    //Jump to the new line
                    i++; 
                } else { //ignore the line and forward
                    while ((i                    if (i>=iBufferLen) return -1;
                    //Jump to the next line
                    i++;
                }
            } else { 
                if (iKeyFound != 0) { //Section has not found, ignore the line
                    while ((i                    if (i>=iBufferLen) return -1;
                    //Jump to the new line
                    i++;
                } else { //it may be the Identity to be found, judge it
                    if (strncmp(szBuffer+i, pIdent, strlen(pIdent))==0) {
                        i += strlen(pIdent);
                        if (i>=iBufferLen) return -1;
                        while ((i                               ((szBuffer[i]=='\t') || (szBuffer[i]==' '))) i++;
            if (szBuffer[i] == '=') { //Value has found
                            i++;
                            while ((i     &nb, sp;                         ((szBuffer[i]=='\t') || (szBuffer[i]==' '))) i++;
                            if (i>=iBufferLen) return -1;
                            j=i;
                            while ((j                               (szBuffer[j]!='\n')) j++; j--;
                            while ((szBuffer[j]==' ') || 
                               (szBuffer[j]=='\t')) j--;
                            min = j-i+1;
                            strncpy(pResult, szBuffer+i, min);
                            *(pResult+min) = '\0';
                            return 0;                             
                        } else { //ignore the line
                        while ((i                        if (i>=iBufferLen) return -1;
                        //Jump to the next line
                        i++;
                    }
 
                    } else { //ignore the line
                        while ((i                        if (i>=iBufferLen) return -1;
                        //Jump to the next line
                        i++;
                    }
                }
            }
        }
    }
    return -1;
}


/**********************************************
Name   : SetIniString
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                char *pValue:  Identity Value to write
Output :
        0: value is successfully written
               -1: parameter error or file not open
Process: Normal 
***********************************************/
int SetIniString(const char *pSection,const char *pIdent,const char *pValue)
{
    int i=0; 
    int j=0; 
    int k=0;
    int iBufferMore = 0;
    int bKeyFound=0,bIdentFound=0;
    int iKeyPos=0,iIdentPos=0;

    //Parameter is empty or file has not been openned
    if (!strlen(pSection) || !strlen(pIdent) || (fp == NULL)) return -1;

    while (i        while ((i               ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
        if (i>=iBufferLen) break;
        if (szBuffer[i]=='#') { //ignore the lines beginning with '#'
            while ((i            if (i>=iBufferLen) break; 
            //Jump to the next line
            i++;
        } else {
            if (szBuffer[i]=='[') {
                i++;
                while ((i                       ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                if (i>=iBufferLen) break;
                if (strncmp(szBuffer+i, pSection, strlen(pSection))==0) { 
                    //key may be found, let's see
                    i += strlen(pSection);
                    while ((i                           ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                    if (i>=iBufferLen) break;
                    if (szBuffer[i]==']') bKeyFound=1; i++;
                    //matched ] or not, ignore the line
                    while ((i                    if (i>=iBufferLen) break;
                    //Jump to the new line
                    i++;  
    iKeyPos = i;
                } else { //ignore the line and forward
                    while ((i                    if (i>=iBufferLen) break;
                    //Jump to the next line
                    i++;
                }
            } else { 
                if (!bKeyFound) { //key has not found, ignore the line
                    while ((i                    if (i>=iBufferLen) break;
                    //Jump to the new line
                    i++;
                } else { //it may be the Identity to be found, judge it
                    if (strncmp(szBuffer+i, pIdent, strlen(pIdent))==0) {
                        i += strlen(pIdent);
                        if (i>=iBufferLen) break;
                        while ((i                               ((szBuffer[i]=='\t') || (szBuffer[i]==' '))) i++;
if (szBuffer[i] == '=') { //Value has found
                            i++; iIdentPos=i;
                            bIdentFound=1;  
                            break;          
                        } else { //ignore the line
                        while ((i                        if (i>=iBufferLen) break;
                        //Jump to the next line
                        i++;
                    }
 
                    } else { //ignore the line
                        while ((i                        if (i>=iBufferLen) break;
                        //Jump to the next line
                        i++;
                    }
                }
            }
        }
    }
    //write lines, if appropriate.
    if (bKeyFound) {
        if (bIdentFound) {
            i=iIdentPos; j=0;
            while ((i            if (strlen(pValue)<=j) {
                //Space is enough, no additional space
                strncpy(szBuffer+iIdentPos, pValue, strlen(pValue));
                for (i=strlen(pValue); i                iBufferMore = 0; 
            } else {
                k = strlen(pValue);
                //Space is limited, need additional space 
                for (i=iBufferLen; i>=iIdentPos+j; i--)
                    szBuffer[i+k-j] = szBuffer[i];
                strncpy(szBuffer+iIdentPos, pValue, strlen(pValue));
                iBufferMore = k-j;
            }
        } else {
            i = strlen(" = \n")+strlen(pIdent)+strlen(pValue);
            for (j=iBufferLen-1; j>=iKeyPos; j--)
                szBuffer[j+i]=szBuffer[j];
            sprintf(szBuffer+iKeyPos, "%s = %s\n", pIdent, pValue);
            iBufferMore = i;
        }
        bBufferChanged = 1;
    } else {
        sprintf(szBuffer+iBufferLen, 
               "\n[%s]\n%s = %s", pSection, pIdent, pValue);
        iBufferMore = strlen("\n[]\n = ")+strlen(pSection)
                          +strlen(pIdent)+strlen(pValue);
        bBufferChanged = 1;
    }
    iBufferLen += iBufferMore;
    return 0;
}

/**********************************************
Name   : GetIniInteger
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                int:  Default Value  if an error exists.
Output :
        interger converted, if applicable
                Default value, if an error exists
                
Process: Normal 
***********************************************/
int GetIniInteger(const char* pSection, const char* pIdent, const int iDefVal)
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    if ( GetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
     if (strlen(szTempBuffer)>2) {
         if ( (szTempBuffer[0]=='0') &&
              ( (szTempBuffer[1]=='x') || (szTempBuffer[1]=='X')) 
            ) return (int)(strtol(szTempBuffer, (char **)NULL, 16));
     }
     return atoi(szTempBuffer);
    } else return iDefVal;
}

/**********************************************
Name   : GetIniLong
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                long:  Default Value  if an error exists.
Output :
        Long converted, if applicable
                Default value, if an error exists
                
Process: Normal 
***********************************************/
long GetIniLong(const char* pSection, const char* pIdent, const long iDefVal)
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    if ( GetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
    if (strlen(szTempBuffer)>2) {
         if ( (szTempBuffer[0]=='0') &&
              ( (szTempBuffer[1]=='x') || (szTempBuffer[1]=='X')) 
            ) return (strtol(szTempBuffer, (char **)NULL, 16));
     }
    return atol(szTempBuffer);
    } else return iDefVal;
}

/**********************************************
Name   : GetIniDouble
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                double:  Default Value  if an error exists.
Output :
        Double converted, if applicable
                Default value, if an error exists
                
Process: Normal 
***********************************************/
double GetIniDouble(const char* pSection, const char* pIdent, const double iDefVal)
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    if ( GetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
return atof(szTempBuffer);
    } else return iDefVal;
}

/**********************************************
Name   : SetIniInteger
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                int:  Value to write
Output :
            0 : Successful
            -1: Error
                
Process: Normal 
***********************************************/
int SetIniInteger(const char *pSection, const char *pIdent, const int pValue)
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    sprintf(szTempBuffer, "%d", pValue);
    if ( SetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
return 0;
    } else return -1;

}

/**********************************************
Name   : SetIniLong
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                long:  Value to write
Output :
            0 : Successful
            -1: Error
                
Process: Normal 
***********************************************/
int SetIniLong(const char *pSection, const char *pIdent, const long pValue) 
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    sprintf(szTempBuffer, "%ld", pValue);
    if ( SetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
return 0;
    } else return -1;

}

/**********************************************
Name   : SetIniDouble
Input  : 
                char *pSection  :  Session Name
                char *pIdent:  Identity Name
                double:  Value to write
Output :
            0 : Successful
            -1: Error
                
Process: Normal 
***********************************************/
int SetIniDouble(const char *pSection, const char *pIdent, const double pValue)
{
    char szTempBuffer[MAX_VALUE_BUFFER_SIZE];
    sprintf(szTempBuffer, "%g", pValue);
    if ( SetIniString(pSection, pIdent, szTempBuffer) == 0 ) {
return 0;
    } else return -1;

}

/**********************************************
Name   : GetSectionValues
Input  : 
                char *pSection  :  Session Name
                char *pDelimiter:  Delimiter to separate values in the section
                char *pValues   :  Buffer to store returned values in the section
Output :
            0 : Successful
            -1: Error
                
Process: Normal 
***********************************************/
int GetSectionValues(const char *pSection, const char *pDelimiter, char *pValues)
{
    int i=0;
    int j=0; 
    int min;
    int iKeyFound=-1;
    int iDelimLen=strlen(pDelimiter);
    int iSum=0;
    
    if (!strlen(pSection) || !strlen(pDelimiter) || (fp == NULL)) return -1;
    
    while (i        while ((i               ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
        if (i>=iBufferLen) break;
        if (szBuffer[i]=='#') { //ignore the lines beginning with '#'
            while ((i            if (i>=iBufferLen) break; 
            //Jump to the next line
            i++;
        } else {
            if (szBuffer[i]=='[') {
                i++;
                while ((i                       ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                if (i>=iBufferLen) break;
                if (strncmp(szBuffer+i, pSection, strlen(pSection))==0) { 
                    //key may be found, let's see
                    i += strlen(pSection);
                    while ((i                           ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
                    if (i>=iBufferLen) break;
                    if (szBuffer[i]==']') {
                     if (iKeyFound==0) break; else iKeyFound=0;
                    } else { if (iKeyFound==0) break; }
                    i++;
                    //matched ] or not, ignore the line
                    while ((i                    if (i>=iBufferLen) break;
                    //Jump to the new line
                    i++; 
                } else { //ignore the line and forward
                    i += strlen(pSection);
                    while ((i                           (szBuffer[i]!=']')) i++;
                    if (i>=iBufferLen) break;
                    if (szBuffer[i] == '\n') { i++; continue; }
                    if ( iKeyFound == 0 ) break;
                    else {
                        while ((i                        if (i>=iBufferLen) break;
                        //Jump to the next line
                        i++;
                    }
                }
            } else { 
                if (iKeyFound != 0) { //key has not found, ignore the line
                    while ((i                    if (i>=iBufferLen) return -1;
                    //Jump to the new line
                    i++;
                } else { //it may be the Identity to be found, judge it
                    while ((i                           (szBuffer[i] != '=')) i++;
                    if (i>=iBufferLen) break;
                    if (szBuffer[i] == '\n') { i++; continue; }
                    i++;
                    while ((i                           ((szBuffer[i]=='\t') || (szBuffer[i]==' '))) i++;
        if (i>=iBufferLen) break;
                    j=i;
                    while ((j                           (szBuffer[j]!='\n')) j++; j--;
                    while ((szBuffer[j]==' ') || 
                           (szBuffer[j]=='\t')) j--;
                    min = j-i+1;
                    strncpy(pValues+iSum, szBuffer+i, min);
                    iSum += min;
                    strncpy(pValues+iSum, pDelimiter, iDelimLen);
                    iSum += iDelimLen;
                    //Jump to the new line
                    i=j+1;
                    while ((i                    if (i>=iBufferLen) break;
                    //Jump to the next line
                    i++;                             
                }
            }
        }
    }
    *(pValues+iSum)='\0';
    return 0;
}

/**********************************************
Name   : GetSections
Input  : 
                char *pDelimiter:  Delimiter to separate sections in the file
                char *pSection   : Buffer to store returned sections in the file
Output :
            0 : Successful
            -1: Error
                
Process: Normal 
***********************************************/
int GetSections(const char *pDelimiter, char *pSections)
{
    int i=0;
    int j=0; 
    int iSum=0;
    int iDelimLen=strlen(pDelimiter);
    
    if (!strlen(pDelimiter) || (fp == NULL)) return -1;
    
    while (i        while ((i               ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
        if (i>=iBufferLen) break;
        if ( szBuffer[i]=='[' ) {
         i++;
            while ((i                  ((szBuffer[i]==' ') || (szBuffer[i]=='\t'))) i++;
            if (i>=iBufferLen) break;
            j=i;
            while ((j                   (szBuffer[j]!=']')) j++; 
            if ((j>=iBufferLen)) break;
            if ((szBuffer[j]=='\n')) { i++; continue; }//Jump to the new line
            j--;
            while ((szBuffer[j]==' ') || (szBuffer[j]=='\t')) j--;
            strncpy(pSections+iSum, szBuffer+i, j-i+1);
            iSum += j-i+1;
            strncpy(pSections+iSum, pDelimiter, iDelimLen);
            iSum += iDelimLen;
            //Jump to the new line
            i=j+2;
            while ((i            if (i>=iBufferLen) break; 
            //Jump to the next line
            i++; 
        } else { //ignore the lines beginning with '#'
            while ((i            if (i>=iBufferLen) break; 
            //Jump to the next line
            i++;
        }
    }
    *(pSections+iSum)='\0';
    return 0;
}

#endif
 

阅读(1185) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~