Qt修改文件内容

在用Qt进行嵌入式开发的时候,有时需要通过界面永久的改变ip地址等网卡信息。此时只能修改系统中包含网卡信息的文件,下图红框中所示就是文件中的网卡信息。

那么如何修改这四行呢,我的做法是先打开该文本文件,然后读出全部文本内容,根据换行符“ ”将文本内容分割为字符串列表,当列表中的某个字符串内容是“iface eth0 inet static”的时候,就可以开始处理接下来读到的四行内容了,这里的关键是如何替换这四行内容,其实通过QString的replace方法就能轻松的进行替换。代码如下所示。

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. QString strAll;  
  2.  QStringList strList;  
  3.  QFile readFile("test.txt");  
  4.  if(readFile.open((QIODevice::ReadOnly|QIODevice::Text)))  
  5.  {  
  6.      QTextStream stream(&readFile);  
  7.      strAll=stream.readAll();  
  8.  }  
  9.  readFile.close();  
  10.  QFile writeFile("test.txt");  
  11.  if(writeFile.open(QIODevice::WriteOnly|QIODevice::Text))  
  12.  {  
  13.          QTextStream stream(&writeFile);  
  14.          strList=strAll.split(" ");  
  15.          for(int i=0;i<strList.count();i++)  
  16.          {  
  17.              if(i==strList.count()-1)  
  18.              {  
  19.                  //最后一行不需要换行  
  20.                  stream<<strList.at(i);  
  21.              }  
  22.              else  
  23.              {  
  24.                  stream<<strList.at(i)<<' ';  
  25.              }  
  26.   
  27.              if(strList.at(i).contains("iface eth0 inet static"))  
  28.              {  
  29.                  QString tempStr=strList.at(i+1);  
  30.                  tempStr.replace(0,tempStr.length(),"        address 192.168.1.111");  
  31.                  stream<<tempStr<<' ';  
  32.                  tempStr=strList.at(i+2);  
  33.                  tempStr.replace(0,tempStr.length(),"        netmask 255.255.255.0");  
  34.                  stream<<tempStr<<' ';  
  35.                  tempStr=strList.at(i+3);  
  36.                  tempStr.replace(0,tempStr.length(),"        network 192.168.1.0");  
  37.                  stream<<tempStr<<' ';  
  38.                  tempStr=strList.at(i+4);  
  39.                  tempStr.replace(0,tempStr.length(),"        geteway 192.168.1.1");  
  40.                  stream<<tempStr<<' ';  
  41.                  i+=4;  
  42.              }  
  43.          }  
  44.  }  
  45.  writeFile.close();  

修改后的文件如下图所示。

http://blog.csdn.net/caoshangpa/article/details/51775147

原文地址:https://www.cnblogs.com/findumars/p/5702201.html