#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>#define CFGFILE "CfgFile.conf"
/***************************************************************
*函数名:GetCfgVal
*参数:cFileName 配置文件名 key要查的键 value 查到的值
*返回值:成功返回1,并把值存到value;失败返回 0
*功能:从基本的配置文件中读取配置.
****************************************************************/
int GetCfgVal(char* cFileName,char *key,char* value)
{
FILE *fOpen;
char cBuf[512] = {0};
char tmpBuf[512];
char *p,*q;
int nRet = 0;fOpen = fopen(cFileName,"r");
if(fOpen != NULL)
{
while(!feof(fOpen))
{
fgets(cBuf,sizeof(cBuf),fOpen);
if(cBuf[0] == '#')
continue;
strcpy(tmpBuf,cBuf);
q =p = strchr(tmpBuf,'=');
if(p > 0)
{
while(*p&&*(p-1)==' ') p--;
*p = 0;
if(strcmp(tmpBuf,key)==0)
{
nRet = 1;
q++;
while(*q && *q==' ') q++;
if(q[strlen(q)-1]=='\n')
q[strlen(q)-1]=0;
strcpy(value,q);
}
}
}}else
{
nRet = 0;
}
fclose(fOpen);
return nRet;
}int main(int argc, char* argv[])
{
char buf[256]={0};
char key[][256] = {"IP","PORT","SERVERNAME","HOMEDIR","USER","PASSWORD"};
int i;
printf("\n\tCfgFileParse Example.\n");for(i=0;i<6;i++)
if(GetCfgVal(CFGFILE,key[i],buf))
printf("%s:%s\n",key[i],buf);
else
printf("Failed to get %s\n",key[i]);
return 0;
}
C简单的配置文件操作
最新推荐文章于 2022-10-18 10:00:00 发布