[Qt] Qt删除文本文件中的某一行

需求

我们经常读一个文件或者直接往一个空白文件中写文本,那么该如何使用Qt在一个文本文件中删除某一行

代码

cpp 复制代码
#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();
}
相关推荐
Quz2 天前
QML Hello World 入门示例
qt
xcyxiner5 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner6 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner6 天前
DicomViewer (添加模型类)3
qt
xcyxiner7 天前
DicomViewer (目录调整) 2
qt
xcyxiner7 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能9 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G9 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
森G9 天前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt
森G9 天前
71、打包发布---------打包发布
c++·qt