读取配置

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_CONFIG_LEN 512

void OI_CFG_STR(char *sConfigFilePath,char *sKey,char *sValue)
{
	FILE *pstFile;
	char sLine[MAX_CONFIG_LEN]={0};
	char *pCurLine=NULL;
	char *del=" ";
	char *pStr=NULL;
	if((pstFile=fopen(sConfigFilePath,"r"))==0)
	{
		printf("Cannot Open!\n");
		return ;
	}
	while(1)
	{
		pCurLine = fgets(sLine,sizeof(sLine),pstFile);
		if(pCurLine==NULL)
			break;
		pStr = strtok(pCurLine,del);
		while(pStr != NULL)
		{
			if(strcmp(pStr,sKey)==0)
			{
				pStr = strtok(NULL,del);
				strcpy(sValue,pStr);
				break;
			}
			pStr=strtok(NULL,del);
		}

		if(feof(pstFile))
			break;
	}
}
int main(void)
{
	char sConfigFilePath[1024]="D://config.txt";
	char sKey[16]="PORT";
	char sValue[1024]={0};
	OI_CFG_STR(sConfigFilePath,sKey,sValue);
	printf("key:%s,value:%s\n",sKey,sValue);
	return 0;
}

 

posted on 2017-01-24 14:34  ″ Jerry。  阅读(105)  评论(0编辑  收藏  举报