您的位置:首页 > 其它

C简单的配置文件操作

2011-12-21 14:50 411 查看
 

#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 include null file user