linux怎么读取配置文件,读取配置文件GetProfileString(linux版)

读取配置文件GetProfileString(linux版)

文件格式:

注:“=”旁边不能有空格,若需空格,加trim函数

[DBCONFIG] DBSERVERIP=193.168.1.8 USER=sa PASSWORD=sa DATABASE=test PORT=1433

文件读取函数:

#include #include #include //#include #include "malloc.h" #include "FileReader.h" #define KEYVALLEN 30 char * l_trim(char *str) { int iLen; int i; char *buf; int iDstLen; char ch; iLen = strlen(str); for(i = 0; i < iLen; i++) { ch = str[i]; if(!(ch == ' ' || ch == '/n' || ch == '/r' || ch == '/t')) { break; } } if(i == 0) { return str; } iDstLen = iLen - i; buf = (char *)malloc(iDstLen + 1); if(buf == NULL) { return buf + 1; } strcpy(buf, str + i); return buf; } int CFileReader::GetProfileString(char * profile, char * AppName, char * KeyName, char * KeyVal ) { char appname[20],keyname[20]; char buf[KEYVALLEN],*c; FILE *fp; int found=0; /* 1 AppName 2 KeyName */ 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]", AppName ); memset( keyname, 0, sizeof(keyname) ); while( !feof(fp) && fgets( buf, KEYVALLEN, fp )!=NULL ){ if( l_trim( buf )==0 ) continue; 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, KeyName)==0 ){ sscanf( ++c, "%[^/r/n]", KeyVal ); found=2; break; } else { continue; } } } } fclose( fp ); if( found==2 ) return(0); else return(-1); }

调用处代码:

char dbServerIP[20]; char user[20]; char password[20]; char database[20]; char dbPort[10]; char httpPort[10]; int port; CFileReader reader; memset(.....); reader.GetProfileString("Config.cfg","DBCONFIG","DBSERVERIP",dbServerIP); reader.GetProfileString("Config.cfg","DBCONFIG","USER",user); reader.GetProfileString("Config.cfg","DBCONFIG","PASSWORD",password); reader.GetProfileString("Config.cfg","DBCONFIG","DATABASE",database); reader.GetProfileString("Config.cfg","DBCONFIG","PORT", dbPort); sscanf(dbPort,"%d", &port);

转载自:http://blog.chinaunix.net/u/1574/showart_2033919.html

http://blog.sina.com.cn/s/blog_4758a67c0100cts2.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值