在用Qt進行嵌入式開發的時候,有時需要通過界面永久的改變ip地址等網卡信息。此時只能修改系統中包含網卡信息的文件,下圖紅框中所示就是文件中的網卡信息。
那么如何修改這四行呢,我的做法是先打開該文本文件,然后讀出全部文本內容,根據換行符“\n”將文本內容分割為字符串列表,當列表中的某個字符串內容是“iface eth0 inet static”的時候,就可以開始處理接下來讀到的四行內容了,這里的關鍵是如何替換這四行內容,其實通過QString的replace方法就能輕松的進行替換。代碼如下所示。
- QString strAll;
- QStringList strList;
- QFile readFile("test.txt");
- if(readFile.open((QIODevice::ReadOnly|QIODevice::Text)))
- {
- QTextStream stream(&readFile);
- strAll=stream.readAll();
- }
- readFile.close();
- QFile writeFile("test.txt");
- if(writeFile.open(QIODevice::WriteOnly|QIODevice::Text))
- {
- QTextStream stream(&writeFile);
- strList=strAll.split("\n");
- for(int i=0;i<strList.count();i++)
- {
- if(i==strList.count()-1)
- {
- //最后一行不需要換行
- stream<<strList.at(i);
- }
- else
- {
- stream<<strList.at(i)<<'\n';
- }
- if(strList.at(i).contains("iface eth0 inet static"))
- {
- QString tempStr=strList.at(i+1);
- tempStr.replace(0,tempStr.length()," address 192.168.1.111");
- stream<<tempStr<<'\n';
- tempStr=strList.at(i+2);
- tempStr.replace(0,tempStr.length()," netmask 255.255.255.0");
- stream<<tempStr<<'\n';
- tempStr=strList.at(i+3);
- tempStr.replace(0,tempStr.length()," network 192.168.1.0");
- stream<<tempStr<<'\n';
- tempStr=strList.at(i+4);
- tempStr.replace(0,tempStr.length()," geteway 192.168.1.1");
- stream<<tempStr<<'\n';
- i+=4;
- }
- }
- }
- writeFile.close();
修改后的文件如下圖所示。
http://blog.csdn.net/caoshangpa/article/details/51775147