【发布时间】:2012-03-09 13:49:39
【问题描述】:
目标:要打开配置文件,查找具有标签的特定行并更改其值
示例:
config .txt
bla bla
bla bla
SYSTEM_A_EXTERNAL_IP=192.168.0.57 // need to change ip address
bla bla
bla bla
到目前为止我所做的: 我的代码打开文件并查找具有标记的特定行并更改其值。
问题:我没有在实际文件中看到这些更改。我知道 ofstream 将写入行,但如果我使用 ofstream 而不是 ifstream getline 函数会出错。
代码1:
bool SetIpAddr(string & iAddr)
{
bool check= false;
// Open file
ifstream iFile(IpConfigFile.c_str(), ios_base::out|ios::app | ios::binary);
if(iFile.is_open())
{
check= true;
}
// Read content of ipconf file searching for the value of Head Id Name
if(true == check)
{
string TargetName = SystemAIdValue + ExternalIpNamePostfix+ ValueAssignmentCharacter;
string outbuf;
while( !iFile.eof() )
{
getline(iFile, outbuf);
// find the matching string
if( 0 == outbuf.compare(0,TargetName.size(),TargetName) )
{
outbuf.erase(outbuf.begin()+TargetName.size(), outbuf.end());
outbuf.insert(0+TargetName.size(), iAddr);
std::cout<< " after insertion " << outbuf << std::endl;
break;
}
}
}
// Close (input) file
if( iFile.is_open() )
{
iFile.close();
}
return check;
}
Code2:也不行。
bool SetIpAddr(string & aIpAddr)
{
bool lResult = false;
std::fstream ifile("platform_ip_config");
string lTargetIp = HeadAIdValue + ExternalIpNamePostfix+ ValueAssignmentCharacter;
std::deque<std::string>lines;
std::string inbuf;
while( std::getline(ifile, inbuf));
{
std::cout<<" we are in while"<<std::endl;
std::cout<<" getline =="<< inbuf<< std::endl;
std::cout<<" ip =="<<lTargetIp<< std::endl;
if( 0 == inbuf.compare(0,lTargetIp.size(),lTargetIp) )
{
std::cout<<" we are in matching"<<std::endl;
std::cout<< inbuf << std::endl;
inbuf.erase(inbuf.begin()+lTargetIp.size(), inbuf.end());
std::cout<<" after erase " << inbuf << std::endl;
inbuf.insert(0+lTargetIp.size(), aIpAddr);
std::cout<< " after insertinon " << inbuf << std::endl;
}
lines.push_back(inbuf);
}
ifile.seekg (0, ios::beg );
std::copy(lines.begin(), lines.end(),
std::ostream_iterator<std::string>(ifile, "\n"));
}
lines.push_back(inbuf);
}
ifile.seekg (0, ios::beg );
std::copy(lines.begin(), lines.end(),
std::ostream_iterator<std::string>(ifile, "\n"));
}
【问题讨论】:
-
ifstream = 输入文件流,ofstream = 输出文件流。如果你想要两者:fstream。
-
我尝试过使用 fstream 但在这种情况下 getline 函数不起作用。在发布之前,我添加了一些调试语句来检查它
-
它不允许粘贴配置文件的所有内容。配置文件的文件权限为 777,以防万一
标签: c++