代码: 全选
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <fstream>
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
bool openfile(string filename,string &Str)
{
ifstream infile(filename.c_str());
if(!infile)
{
cerr<<"Error:unable to open file '"<<filename<<"'"<<endl;
return false;
}
string temp;
while(infile>>temp)
{
Str+=temp;
Str+='\n';
}
infile.close();
return true;
}
string findip(string contents,const string &inString)
{
string::size_type pos=inString.find(contents.c_str());
if (pos>inString.size())
{
cerr<<"No '"<<contents<<"' in the file this file."<<endl;
exit(-1);
}
while(inString[pos]!=':') ++pos;
++pos;
string ip;
while(inString[pos]!='\n')
{
ip+=inString[pos];
++pos;
}
return ip;
}
void replace(string &originally,string source,string target)
{
string::size_type start=originally.find(source.c_str()),end=0;
while(originally[start]!='=')
{
++start;
}
++start;
end=start;
while(originally[end]!='\n') ++end;
// string::iterator tmp;
originally.erase(start,end-start);
originally.insert(start,target);
}
void writefile(string filename,string &contants)
{
ofstream outfile(filename.c_str());
outfile<<contants<<endl;
outfile.close();
}
int main(int argc, char *argv[])
{
string ipfile,ip,drcom;
system("ifconfig> /tmp/temp_ip");
if(!openfile("/tmp/temp_ip",ipfile)) return -1;
ip=findip("地址:",ipfile);
system("rm /tmp/temp_ip");
if(!openfile("/etc/drcom.conf",drcom)) return -1;
replace(drcom,"nic0=",ip);
writefile("/etc/drcom.conf",drcom);
cout<<"IP update successful."<<endl;
return EXIT_SUCCESS;
}