微软把程序猿养懒了。如果你在windows里写程序,那么本文你可以不看,有GetPrivateProfileString等来读取;如果你在qt里写程序,那么本文也可以不看。如果你在linux或者mac下写纯c或者c++程序,而需要读取参数配置文件....Oh,My god.Shit Bill Gates.
对应的配置文件如下:
[SectionName]
field_name1=value
field_name2=value
field_name3=number
但是,很抱歉,目前本文里的函数不支持SectionName段名,field_name字段名必须不同哈。
1.定位函数,在buffer字符串里,按照字符串keyword找到开始位置,返回开始位置,没找到则返回-1:
int config_find(char * buffer,unsigned long len,char *keyword)
{
int i=0;
for(i=0;i
{
if(strncmp((buffer+i),keyword,strlen(keyword))==0)
{
return i;
}
}
return -1;
}2.读取整型参数,成功返回该值。失败返回-65535。
int config_profile_int(char *buffer,unsigned long buflen,char *keyword)
{
int firstpos=config_find(buffer,buflen,keyword);//strstr(pchStr,"<10001>")+strlen("<10001>");
// printf("%d,char size:%lu",firstpos,strlen(keyword));
if(firstpos==-1)
return -65535;
firstpos+=strlen(keyword);
unsigned long kwlen=config_find((buffer+firstpos),buflen-firstpos,(char *)"\n");
if(kwlen==-1)//可能是文件末尾没有回车
kwlen=buflen-firstpos;
// printf("\nend pos :%d",kwlen);
char *val1=new char[kwlen];
memcpy(val1,(buffer+firstpos),kwlen);
// printf("\n%s",val1);
int ivalue=atoi(val1);
delete val1;
return ivalue;
}3.读取字符型参数。读取成功返回字符串,失败返回空字符串“”,带了个末尾的'\0'。啰嗦几句:
win下一个回车键产生\r\n两个字节,linux下一个回车键产生\n一个字节。该函数已通用win和lnx。
char *config_profile_string(char *buffer,unsigned long buflen,char *keyword)//读取字符
{
int firstpos=config_find(buffer,buflen,keyword);
if(firstpos==-1)
return (char *)"";
firstpos+=strlen(keyword);
unsigned long kwlen=config_find((buffer+firstpos),buflen-firstpos,(char *)"\r");//先找windows回车开始字符
if(kwlen==-1)//可能是linux文件的回车
kwlen=config_find((buffer+firstpos),buflen-firstpos,(char *)"\n");//找linux回车开始字符
if(kwlen==-1)//可能是文件末尾没有回车
kwlen=buflen-firstpos;
char *val1=new char[kwlen+1];
// memcpy(val1,(buffer+firstpos),kwlen);
strncpy(val1,(buffer+firstpos),kwlen);
val1[kwlen]='\0';//字符串结尾一定要加\0,不然会产生不可预知的问题.某些linux会初始化内存空间为全0;而mac不会
// printf("wocao:\n%s",val1);
return val1;
}
附录:
和微软的弓虽函数比起来,本文的这2个函数就弱了。主要是可以从段名里读取参数。下面介绍下微软的这2个NB函数。
得到整型参数。
UINT GetPrivateProfileInt( LPCTSTRlpAppName,// address of section name
LPCTSTRlpKeyName,// address of key name
INTnDefault,// return value if key name is not found
LPCTSTRlpFileName // address of initialization filename
);
得到字符串参数。
DWORD GetPrivateProfileString( LPCTSTRlpAppName,// points to section name
LPCTSTRlpKeyName,// points to key name
LPCTSTRlpDefault,// points to default string
LPTSTRlpReturnedString,// points to destination buffer
DWORDnSize,// size of destination buffer
LPCTSTRlpFileName // points to initialization filename
);