/***************************************************************
/* 函 数 名:GetPrivateProfileString
/* 函数功能:C语言版GetPrivateProfileString()函数,从文件中读
/* 出指定的条目的字串
/* 参 数:
/* strSectionName:欲在文件中查找条目的小节名称
/* strKeyName: 欲获取的项名或条目名
/* strFileName: 文件名
/* strRet: 项名或条目名中的内容,返回
/* 返 回 值:
/* 获取成功返回0
/* 获取失败返回-1
/*
/* 作 者:X攻城狮
/* 修改日期:2015年11月7日
/***************************************************************/
int GetPrivateProfileString(const char *strSectionName, const char *strKeyName, const char *strFileName, char *strRet)
{
memset(strRet,0,strlen(strRet+1));
FILE *fp = fopen(strFileName,"r");
if(NULL == fp)
{
return -1;
}
fseek(fp,0L,SEEK_END);
int iSize=ftell(fp);
fseek(fp,0L,SEEK_SET);
char *strBuffer = (char *)malloc(iSize);
memset(strBuffer, 0, iSize);
fread(strBuffer, iSize, 1, fp);
int iPos1=0, iPos2=0, iPos3=0, iRet = 0;
while(1)
{
iPos1 = FindSubstring(strBuffer+iPos3, "[");
if (-1 == iPos1)
{
iRet = -1;
break;
}
iPos1 += iPos3;
iPos2 = FindSubstring(strBuffer+iPos1, "]");
if (-1 == iPos1)
{
iRet = -1;
break;
}
iPos2 += iPos1;
iPos3 = FindSubstring(strBuffer+iPos2, "[");
iPos3 = iPos3 == -1 ? iSize : iPos3+iPos2;
int iPos4 = FindSubstring(strBuffer+iPos1, strSectionName);
if((iPos4 != -1) && (iPos4 < iPos3))
{
iPos4 += iPos1;
int iPos5 = FindSubstring(strBuffer+iPos2, strKeyName);
if((iPos5 != -1) && (iPos5 < iPos3))
{
iPos5 += iPos2;
int iPos6 = FindSubstring(strBuffer+iPos5, "=");
if((iPos6 != -1) && (iPos6 < iPos3))
{
iPos6 += iPos5;
int i = iPos6+1, j = 0;
while(strBuffer[i] != '\n')
{
if(strBuffer[i] != ' ')
{
strRet[j++] = strBuffer[i];
}
i++;
}
iRet = 0;
break;
}
else
{
iRet = -1;
}
}
else
{
iRet = -1;
}
}
else
{
iRet = -1;
}
}
if(fclose(fp)!=0)
{
return -1;
}
else
{
return iRet;
}
}
/***************************************************************
/* 函 数 名:FindSubstring
/* 函数功能:C语言版,在字符串中查找子串
/* 参 数:
/* strSource:待查找的源字符串
/* strSub: 要查找的子串
/* 返 回 值:
/* 查找成功返回子串首字符在源串中的位置
/* 查找失败返回-1
/*
/* 作 者:X攻城狮
/* 修改日期:2015年11月7日
/***************************************************************/
int FindSubstring (const char *strSource, const char *strSub)
{
int iRet = -1;
unsigned int uLen = strlen(strSource);
if (uLen == 0)
{
return iRet;
}
char *str1 = (char *)malloc(uLen+1);
memset(str1, 0, uLen+1);
strcpy(str1, strSource);
uLen = strlen(strSub);
if (uLen == 0)
{
free(str1);
return iRet;
}
char *str2 = (char *)malloc(uLen+1);
memset(str2, 0, uLen+1);
strcpy(str2, strSub);
unsigned int i = 0, j = 0;
for(i=0; i<=strlen(strSource); i++)
{
if (str1[i] == str2[j])
{
if (j+1 == uLen)
{
iRet = i + 1- uLen;
break;
}
else
{
j++;
}
}
else
{
j = 0;
iRet = -1;
}
}
free(str1);
free(str2);
return iRet;
}