c代码读取ini文件

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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值