需求
我们经常读一个文件或者直接往一个空白文件中写文本,那么该如何使用Qt在一个文本文件中删除某一行
代码
#include <QCoreApplication>
#include <QIODevice>
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);QFile file(QStringLiteral("F:/QTCode/deleteLineInFile/新建文本文档.txt"));QString allText;if(file.open(QIODevice::ReadWrite)){QTextStream stream(&file);stream.setCodec("UTF-8");while(!stream.atEnd()){QString lineStr = stream.readLine();if(lineStr == QStringLiteral("也是")){continue;}allText.append(lineStr);if(!stream.atEnd()){allText.append('\r');allText.append('\n');}}file.close();if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)){file.write(allText.toUtf8());file.close();qDebug() << QStringLiteral("操作成功");}else{qDebug() << QStringLiteral("写文件失败");}}else{qDebug() << QStringLiteral("打开文件失败");}return a.exec();
}