您的位置:首页 > 编程语言 > Qt开发

Qt修改文件内容

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



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

[cpp] view plain copy







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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: