引用来源:C语言读取配置文件代码 http://www.iamlicky.cn/post/192.html
稍作修改。
readconf.h
#ifndef READCONF_H
#define READCONF_H
#include "stdio.h"
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#define CONLINELENGTH 100 //配置文件一行的长度最大值
int GetProfileString(const char *profile, char *appName, char *keyName, char *keyVal );
#endif
readconf.c
#include "readconf.h"
/**************************
*http://www.iamlicky.cn/post/192.html
*函数功能:读取配置文件信息
*输入参数:配置文件的名字profile,
*输出结果:项目信息
*返回值:成功返回1,否则返回0
*******************************/
int GetProfileString(const char *profile, char *app, char *key, char *val )
{
char appname[20],keyname[20];
char buf[CONLINELENGTH],*c;
FILE *fp;
int found=0; /* 1 app 2 key */
if( (fp=fopen( profile,"r" ))==NULL ){
printf( "openfile [%s] error [%s]\n", profile,strerror(errno));
return(-1);
}
fseek( fp, 0, SEEK_SET );
sprintf( appname,"%s", app );
memset( keyname, 0, sizeof(keyname) );
while( !feof(fp) && fgets( buf,CONLINELENGTH,fp )!=NULL ){
if( found==0 ){
if( buf[0]!='[' ){
continue;
}
else if ( strncmp(buf,appname,strlen(appname))==0 ){
found=1;
continue;
}
}
else if( found==1 ){
if( buf[0]=='#' ){
continue;
}
else if ( buf[0]=='[' ){
break;
}
else{
if( (c=(char*)strchr(buf,'='))==NULL )
continue;
memset( keyname, 0, sizeof(keyname) );
sscanf( buf, "%[^=]", keyname );
if( strcmp(keyname, key)==0 ){
sscanf( ++c, "%[^\r]", val);
found=2;
break;
}
else{
continue;
}
}
}
}
fclose( fp );
if( found==2 )
return(0);
else
return(-1);
}
void main()
{
const char *conf_filename="sip.config"; //配置文件的名称
int id=0,port=0;
char cfg[]="[Config]";
char p_id[]="id",p_port[]="port",p_ipType[]="ipType",p_ipAddress[]="ipAddress",p_domainName[]="domainName",p_userName[]="userName",p_userPwd[]="userPwd";
char str_id[20]={0},str_port[20]={0},ipType[20]={0},ipAddress[20]={0},domainName[20]={0},userName[20]={0},userPwd[20]={0};
GetProfileString(conf_filename,cfg,p_id,str_id);
GetProfileString(conf_filename,cfg,p_ipType,ipType);
GetProfileString(conf_filename,cfg,p_ipAddress,ipAddress);
GetProfileString(conf_filename,cfg,p_domainName,domainName);
GetProfileString(conf_filename,cfg,p_port,str_port);
GetProfileString(conf_filename,cfg,p_userName,userName);
GetProfileString(conf_filename,cfg,p_userPwd,userPwd);
if(str_id != NULL)
id = atoi(str_id);
if(str_port != NULL)
port = atoi(str_port);
printf(" id=%d\n ipType=%s\n ipAddress=%s\n domainName=%s\n port=%d\n userName=%s\n userPwd=%s\n",id,ipType,ipAddress,domainName,port,userName,userPwd);
}
sip.config
[Config]
id=1
ipType=NET_DOMAIN_TYPE
ipAddress=10.10.10.10
domainName=dm900.gxstb.com
port=33567
userName=1234
userPwd=123456