ini文件格式:
;注释
[节名]
键=值
...
// 读取ini文件中特定项的值
char * GetInitKey(char *pFilename, char *pSection, char *pKey)
{
static char retstr[1024];
int nFlag = 0;
char tmpLine[1024];
FILE *pFile;
pFile = fopen(pFilename, "r");
if (pFile == NULL)
{
return NULL;
}
while (1)
{
// 是否文件尾
if (fgets(tmpLine, 1024, pFile) == NULL)
{
break;
}
// 忽略注释行
if (tmpLine[0] == ';')
{
continue;
}
// 是否找到节名
if (nFlag == 0)
{
// 该列是否节名
if (tmpLine[0] == '[')
{
int nTitleLen = strlen(pSection);
// 与所查找的节名长度是否相同,节名是否相同
if (tmpLine[nTitleLen + 1] == ']' && strncmp(pSection, tmpLine + 1, nTitleLen) == 0)
{
nFlag = 1;
}
}
}
else
{
// 是否为键值列
//const char *pTemp = strchr(tmpLine, '=');
//if (pTemp != NULL)
int nKeyLen = strlen(pKey);
if (tmpLine[nKeyLen] == '=')
{
//pTemp - tmpLine == nKeyLen &&
if (strncmp(pKey, tmpLine, nKeyLen) == 0)
{
strcpy (retstr, tmpLine + 1 + nKeyLen);
//去掉最后一个换行符
retstr[strlen(retstr) - 1] = 0;
fclose (pFile);
return retstr;
}
}
// 新节名,跳出
else if (tmpLine[0] == '[')
{
break;
}
}
}
fclose (pFile);
return NULL;
}