读取指定路径下文件,并解析提取相关内容。
读取解析成功返回true,失败返回false。
bool Client::ReadFileConfig()
{
char buffer[256];
char strFilePath[] = "/usr/local/etc/socket.config";
std::string strIP;
int iPort;
if(access(strFilePath, F_OK) !=0 )
{
printf("ERROR: config file not exist! Using default IP and Port! \n");
return false;
}
std::ifstream fs;
fs.open( strFilePath);
if(!fs.is_open())
{
memset( buffer, 0, sizeof(buffer));
sprintf(buffer, "Error: open config file failed! filePath=%s ", strFilePath);
printf("%s \n",buffer);
return false;
}
bool bFindIP = false;
bool bFindPort = false;
while( !fs.eof())
{
memset( buffer, 0, sizeof(buffer));
fs.getline( buffer, sizeof( buffer));
printf("%s \n", buffer);
std::string strLine(buffer);
// remove(strLine.begin(), strLine.end(), ' ');
size_t nPos = strLine.find("=");
std::string strKey = strLine.substr(0, nPos);
std::string strValue = strLine.substr( nPos + 1);
if(strKey == "IP")
{
strIP = strValue;
bFindIP = true;
printf("SocketIP=%s \n",strValue.c_str());
}
else if(strKey == "Port")
{
iPort = atoi(strValue.c_str());
bFindPort = true;
printf("SocketPort=%d \n",iPort);
}
}
if(!bFindIP)
{
memset( buffer, 0, sizeof(buffer));
sprintf(buffer, "Error: cannot find IP in config file(IP=xx.xx.xx.xx)! filePath=%s ", strFilePath);
printf("%s \n",buffer);
return false;
}
if(!bFindPort)
{
memset( buffer, 0, sizeof(buffer));
sprintf(buffer, "Error: cannot find Port in config file(Port=XXXX)! filePath=%s ", strFilePath);
printf("%s \n",buffer);
return false;
}
return true;
}