Ojective: To open config file, look for a particular line which has tag and change its value
Example:
config .txt
bla bla
bla bla
SYSTEM_A_EXTERNAL_IP=192.168.0.57 // need to change ip address
bla bla
bla bla
What I have done so far: My code open the file and look for the particular line which has tag and change its value .
Problem: I failed to see those changes in the actual file. I am aware that ofstream will write into line but if I do ofstream instead of ifstream getline function gets an error.
Code1:
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: Also doesnt work.
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"));
}
What you are doing is inherently tricky, writing to the middle of a file hoping the result will remain in place.
for example
uses up a lot more characters than
the way i would do this is read the whole files into lines.
Please note you do not need to explicitly close a file in C++, the RAII semantics will close it for you, by doing it your self your increasing the opportunity for bugs to creep into your code.
THIS WORKS ON MY SYSTEM