七、文件与目录操作

一、文本文件读写

文件打开方式
QIODevice::ReadOnly	以只读方式打开
QIODevice::QriteOnly		以只写方式打开
QIODevice::ReadWrite	以读写方式打开
QIODevice::Append		新增加的内容将被追加到文件末尾
QIODevice::Truncate		以重写的方式打开,原有内容会被删除
QIODevice::Text				在读取时,行结束符转换为\n;在写时,将行结束符转换为本地格式,例如:Win32平台是\r\n

1、实现工具

(1)创建项目,基于QMainWindow

(2)添加图标资源文件与组件

七、文件与目录操作_第1张图片

(3)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setCentralWidget(ui->tabWidget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actOpenIODevice_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString dlgTitle = "打开文件";
    QString filter = "程序(*.c *.cpp);;文本(*.txt);;所有文件(*.*)";
    QString strFileName = QFileDialog::getOpenFileName(this,
                          dlgTitle, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        ui->plainTextEditIODevice->setPlainText(
            QString::fromLocal8Bit(file.readAll()));
        file.close();
        ui->tabWidget->setCurrentIndex(0);
    }
}

void MainWindow::on_actSaveIODevice_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString dlgTitle = "保存文件";
    QString filter = "程序(*.c *.cpp);;文本(*.txt);;所有文件(*.*)";
    QString strFileName = QFileDialog::getSaveFileName(this,
                          dlgTitle, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QString str = ui->plainTextEditIODevice->toPlainText();
        QByteArray btArray = str.toUtf8();
        file.write(btArray, btArray.size());
        file.close();
        ui->tabWidget->setCurrentIndex(0);
    }
}

#include 
void MainWindow::on_actOpenStream_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString dlgTitle = "打开文件";
    QString filter = "程序(*.c *.cpp);;文本(*.txt);;所有文件(*.*)";
    QString strFileName = QFileDialog::getOpenFileName(this,
                          dlgTitle, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream stream(&file);

        while (!stream.atEnd())
        {
            ui->plainTextEditTextStream->appendPlainText(stream.readLine());
        }

        //        ui->plainTextEditTextStream->setPlainText(stream.readAll());
        file.close();
        ui->tabWidget->setCurrentIndex(1);
    }
}

void MainWindow::on_actSaveQTextStream_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString dlgTitle = "保存文件";
    QString filter = "程序(*.c *.cpp);;文本(*.txt);;所有文件(*.*)";
    QString strFileName = QFileDialog::getSaveFileName(this,
                          dlgTitle, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream stream(&file);
        QString str = ui->plainTextEditTextStream->toPlainText();
        stream << str;
        file.close();
        ui->tabWidget->setCurrentIndex(1);
    }
}

二、二进制文件读写

使用QFile和QDataStream进行二进制数据的读写
QFile	负责文件的IO设备接口,即与文件物理交互
QDataStream	以数据六的方式读取文件内容或写入文件内容。

1、实现工具

(1)创建项目,基于QMainWIndow

(2)添加图标资源文件,添加组件

七、文件与目录操作_第2张图片

(3)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setCentralWidget(ui->tableView);

    theModel = new QStandardItemModel(this);
    theSelect = new QItemSelectionModel(theModel);
    ui->tableView->setModel(theModel);

    QStringList headerList;
    headerList << "Depth";
    headerList << "Measured Depth";
    headerList << "Direction";
    headerList << "Offset";
    headerList << "Quality";
    headerList << "Sampled";
    theModel->setHorizontalHeaderLabels(headerList);
    resetTable(5);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resetTable(int row)
{
    theModel->removeRows(0, theModel->rowCount());
    theModel->setRowCount(row);

    QString str = theModel->headerData(theModel->columnCount() - 1, Qt::Horizontal,
                                       Qt::DisplayRole).toString();

    for (int i = 0; i < row; ++i)
    {
        //        ui->tableView->setItemDelegateForColumn(0, &intSpinDelegate);
        //        ui->tableView->setItemDelegateForColumn(1, &floatSpinDelegate);
        //        ui->tableView->setItemDelegateForColumn(2, &floatSpinDelegate);
        //        ui->tableView->setItemDelegateForColumn(3, &floatSpinDelegate);
        //        ui->tableView->setItemDelegateForColumn(5, &checkboxDelegate);

        QModelIndex index = theModel->index(i, theModel->columnCount() - 1);
        QStandardItem *item = theModel->itemFromIndex(index);
        item->setData(str, Qt::DisplayRole);
        item->setCheckable(true);
        item->setEditable(false);
    }
}

void MainWindow::on_actTabeset_triggered()
{
    resetTable(10);
}

#include 
void MainWindow::on_actOpen_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString title = "打开文件";
    QString filter = "Qt预定义编码(*.stm)";
    QString strFileName = QFileDialog::getOpenFileName(this, title, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::ReadOnly))
    {
        QDataStream stream(&file);
        stream.setVersion(QDataStream::Qt_5_13);
        qint16 rowCount, colCount;
        stream >> rowCount;
        stream >> colCount;
        resetTable(rowCount);
        /*
        headerList << "Depth";
        headerList << "Measured Depth";
        headerList << "Direction";
        headerList << "Offset";
        headerList << "Quality";
        headerList << "Sampled";
        */
        QString str;

        for (int i = 0; i < colCount; ++i)
        {
            stream >> str;
        }

        qint16 Depth;
        qreal MeasuredDepth, Direction, offset;
        QString Quality;
        bool sampled;

        QModelIndex index;
        QStandardItem *item;

        for (int i = 0; i < rowCount; ++i)
        {
            stream >> Depth;
            index = theModel->index(i, 0);
            item = theModel->itemFromIndex(index);
            item->setData(Depth, Qt::DisplayRole);

            stream >> MeasuredDepth;
            index = theModel->index(i, 1);
            item = theModel->itemFromIndex(index);
            item->setData(MeasuredDepth, Qt::DisplayRole);

            stream >> Direction;
            index = theModel->index(i, 2);
            item = theModel->itemFromIndex(index);
            item->setData(Direction, Qt::DisplayRole);

            stream >> offset;
            index = theModel->index(i, 3);
            item = theModel->itemFromIndex(index);
            item->setData(offset, Qt::DisplayRole);

            stream >> Quality;
            index = theModel->index(i, 4);
            item = theModel->itemFromIndex(index);
            item->setData(Quality, Qt::DisplayRole);

            stream >> sampled;
            index = theModel->index(i, 5);
            item = theModel->itemFromIndex(index);

            if(sampled)
            {
                item->setCheckState(Qt::Checked);

            }
            else
            {
                item->setCheckState(Qt::Unchecked);
            }
        }

        file.close();
    }
}


void MainWindow::on_actSave_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString title = "保存文件";
    QString filter = "标准编码(*.dat)";
    QString strFileName = QFileDialog::getSaveFileName(this, title, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        QDataStream stream(&file);
        stream.setVersion(QDataStream::Qt_5_13);
        qint16 rowCount, colCount;
        rowCount = theModel->rowCount();
        colCount = theModel->columnCount();
        stream << rowCount;
        stream << colCount;

        /*
        headerList << "Depth";
        headerList << "Measured Depth";
        headerList << "Direction";
        headerList << "Offset";
        headerList << "Quality";
        headerList << "Sampled";
        */
        for (int i = 0; i < colCount; ++i)
        {
            stream << theModel->horizontalHeaderItem(i)->text();
        }

        qint16 Depth;
        qreal MeasuredDepth, Direction, offset;
        QString Quality;
        bool sampled;

        for (int i = 0; i < rowCount; ++i)
        {
            auto data = theModel->item(i, 0)->data(Qt::DisplayRole);
            Depth = theModel->item(i, 0)->data(Qt::DisplayRole).toInt();
            stream << Depth;

            MeasuredDepth = theModel->item(i, 1)->data(Qt::DisplayRole).toFloat();
            stream << MeasuredDepth;

            Direction = theModel->item(i, 2)->data(Qt::DisplayRole).toFloat();
            stream << Direction;

            offset = theModel->item(i, 3)->data(Qt::DisplayRole).toFloat();
            stream << offset;

            Quality = theModel->item(i, 4)->data(Qt::DisplayRole).toString();
            stream << Quality;

            if(theModel->item(i, 5)->checkState() == Qt::Checked)
            {
                sampled = true;
            }
            else
            {
                sampled = false;
            }

            stream << sampled;
        }

        file.close();
    }
}

void MainWindow::on_actOpenBin_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString title = "打开文件";
    QString filter = "标准编码(*.dat)";
    QString strFileName = QFileDialog::getOpenFileName(this, title, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::ReadOnly))
    {
        QDataStream stream(&file);
        stream.setByteOrder(QDataStream::LittleEndian);
        stream.setVersion(QDataStream::Qt_5_13);
        qint16 rowCount, colCount;
        //        stream >> rowCount;
        //        stream >> colCount;

        stream.readRawData((char*)&rowCount, sizeof(qint16));
        stream.readRawData((char*)&colCount, sizeof(qint16));

        /*
        headerList << "Depth";
        headerList << "Measured Depth";
        headerList << "Direction";
        headerList << "Offset";
        headerList << "Quality";
        headerList << "Sampled";
        */
        char* buf;
        uint strLen;

        for (int i = 0; i < colCount; ++i)
        {
            //            stream >> str;
            stream.readBytes(buf, strLen);
        }

        qint16 Depth;
        qreal MeasuredDepth, Direction, offset;
        QString Quality;
        qint8 sampled;

        QModelIndex index;
        QStandardItem *item;

        for (int i = 0; i < rowCount; ++i)
        {
            //            stream >> Depth;
            stream.readRawData((char*)&Depth, sizeof(qint16));
            index = theModel->index(i, 0);
            item = theModel->itemFromIndex(index);
            item->setData(Depth, Qt::DisplayRole);

            //            stream >> MeasuredDepth;
            stream.readRawData((char*)&MeasuredDepth, sizeof(qreal));
            index = theModel->index(i, 1);
            item = theModel->itemFromIndex(index);
            item->setData(MeasuredDepth, Qt::DisplayRole);

            //            stream >> Direction;
            stream.readRawData((char*)&Direction, sizeof(qreal));
            index = theModel->index(i, 2);
            item = theModel->itemFromIndex(index);
            item->setData(Direction, Qt::DisplayRole);

            //            stream >> offset;
            stream.readRawData((char*)&offset, sizeof(qreal));
            index = theModel->index(i, 3);
            item = theModel->itemFromIndex(index);
            item->setData(offset, Qt::DisplayRole);

            //            stream >> Quality;
            stream.readBytes(buf, strLen);
            Quality = QString::fromLocal8Bit(buf, strLen);
            index = theModel->index(i, 4);
            item = theModel->itemFromIndex(index);
            item->setData(Quality, Qt::DisplayRole);

            //            stream >> sampled;
            stream.readRawData((char*)&sampled, sizeof(qint8));
            index = theModel->index(i, 5);
            item = theModel->itemFromIndex(index);

            if(sampled)
            {
                item->setCheckState(Qt::Checked);

            }
            else
            {
                item->setCheckState(Qt::Unchecked);
            }
        }

        file.close();
    }
}

void MainWindow::on_actSaveBin_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString title = "保存文件";
    QString filter = "标准编码(*.dat)";
    QString strFileName = QFileDialog::getSaveFileName(this, title, curPath, filter);

    if(strFileName.isEmpty())
    {
        return;
    }

    QFile file(strFileName);

    if(file.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        QDataStream stream(&file);
        stream.setByteOrder(QDataStream::LittleEndian);
        stream.setVersion(QDataStream::Qt_5_13);
        qint16 rowCount, colCount;
        rowCount = theModel->rowCount();
        colCount = theModel->columnCount();
        //        stream << rowCount;
        //        stream << colCount;
        stream.writeRawData((char*)&rowCount, sizeof(qint16));
        stream.writeRawData((char*)&colCount, sizeof(qint16));


        /*
        headerList << "Depth";
        headerList << "Measured Depth";
        headerList << "Direction";
        headerList << "Offset";
        headerList << "Quality";
        headerList << "Sampled";
        */
        QByteArray btArray;

        for (int i = 0; i < colCount; ++i)
        {
            //            stream << theModel->horizontalHeaderItem(i)->text();
            btArray = theModel->horizontalHeaderItem(i)->text().toUtf8();
            stream.writeBytes(btArray, btArray.length());
        }

        qint16 Depth;
        qreal MeasuredDepth, Direction, offset;
        QString Quality;
        int8_t sampled;

        for (int i = 0; i < rowCount; ++i)
        {
            auto data = theModel->item(i, 0)->data(Qt::DisplayRole);
            Depth = theModel->item(i, 0)->data(Qt::DisplayRole).toInt();
            //            stream << Depth;
            stream.writeRawData((char*)&Depth, sizeof(qint16));

            MeasuredDepth = theModel->item(i, 1)->data(Qt::DisplayRole).toFloat();
            //            stream << MeasuredDepth;
            stream.writeRawData((char*)&MeasuredDepth, sizeof(qreal));

            Direction = theModel->item(i, 2)->data(Qt::DisplayRole).toFloat();
            //            stream << Direction;
            stream.writeRawData((char*)&Direction, sizeof(qreal));

            offset = theModel->item(i, 3)->data(Qt::DisplayRole).toFloat();
            //            stream << offset;
            stream.writeRawData((char*)&offset, sizeof(qreal));

            Quality = theModel->item(i, 4)->data(Qt::DisplayRole).toString();
            //            stream << Quality;
            btArray = Quality.toUtf8();
            stream.writeBytes(btArray, btArray.length());

            if(theModel->item(i, 5)->checkState() == Qt::Checked)
            {
                sampled = 1;
            }
            else
            {
                sampled = 0;
            }

            //            stream << sampled;
            stream.writeRawData((char*)&sampled, sizeof(int8_t));

        }

        file.close();
    }
}

三、文件目录操作

文件目录操作相关类:
  • QCoreApplocation:用于提取应用程序路径、程序名等文件信息
  • QFIle:除了打开文件操作外,还有复制文件、删除文件等功能
  • QFileInfo:用于提取文件信息,包括路径、文件名、后缀
  • QDir:用于提取目录或文件,文件重名等操作
  • QTemporaryDir和QTemporaryFile:用于创建临时目录和临时文件
  • QFileSystemWatcher:监听目录下为念的添加和删除等变化

1、实现工具

(1)创建项目,基于QMainWindow

(2)添加组件

七、文件与目录操作_第3张图片

(3)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::getBtnInfo(QObject *btn)
{
    QPushButton* button = static_cast<QPushButton*>(btn);
    ui->plainTextEdit->appendPlainText(button->text());
    ui->plainTextEdit->appendPlainText(button->toolTip());
}

#include 
void MainWindow::on_btnOpenFile_clicked()
{
    QString strCurPath = QDir::currentPath();
    QString strFileName = QFileDialog::getOpenFileName(this, "", strCurPath, "(*.*)");
    ui->lineEditFile->setText(strFileName);
}

void MainWindow::on_btnOpenDir_clicked()
{
    QString strCurPath = QDir::currentPath();
    QString strDirName = QFileDialog::getExistingDirectory(this, "", strCurPath);
    ui->lineEditDir->setText(strDirName);
}

void MainWindow::on_btnClear_clicked()
{
    ui->plainTextEdit->clear();
}
void MainWindow::on_btnApplicationDirPath_clicked()
{
    //    QPushButton* btn = static_cast<QPushButton*>(sender());
    //    ui->plainTextEdit->appendPlainText(btn->text());
    //    ui->plainTextEdit->appendPlainText(btn->toolTip());
    getBtnInfo(sender());
    ui->plainTextEdit->appendPlainText(QCoreApplication::applicationDirPath());
}

void MainWindow::on_btnStaticCopy_clicked()
{
    getBtnInfo(sender());
    QString strSource = ui->lineEditFile->text();
    QFileInfo info(strSource);
    QString strDest = info.path() + "/" + info.fileName() + "-副本." + info.suffix();
    QFile::copy(strSource, strDest);
    ui->plainTextEdit->appendPlainText("源文件: " + strSource);
    ui->plainTextEdit->appendPlainText("副本: " + strDest + "\n");

}

void MainWindow::on_btnMkdir_clicked()
{
    getBtnInfo(sender());
    QDir dir(ui->lineEditDir->text());

    if(dir.mkdir("newDir"))
    {
        ui->plainTextEdit->appendPlainText("创建成功");
    }
    else
    {
        ui->plainTextEdit->appendPlainText("创建失败");
    }
}

void MainWindow::on_btnAddPath_clicked()
{
    getBtnInfo(sender());
    ui->plainTextEdit->appendPlainText("监听目录:" + ui->lineEditDir->text());
    fileWatcher.addPath(ui->lineEditDir->text());
    fileWatcher.addPath(ui->lineEditFile->text());

    QObject::connect(&fileWatcher, &QFileSystemWatcher::directoryChanged,
                     this, MainWindow::on_dirctoryChanged);
    QObject::connect(&fileWatcher, &QFileSystemWatcher::fileChanged,
                     this, MainWindow::on_fileChanged);

}

void MainWindow::on_fileChanged()
{
    ui->plainTextEdit->appendPlainText("监听到文件");
}

void MainWindow::on_dirctoryChanged()
{
    ui->plainTextEdit->appendPlainText("监听到目录");
}

void MainWindow::on_btnRemovePath_clicked()
{
    getBtnInfo(sender());
    ui->plainTextEdit->appendPlainText("监听目录:" + ui->lineEditDir->text());
    fileWatcher.removePath(ui->lineEditDir->text());
    fileWatcher.removePath(ui->lineEditFile->text());

    QObject::disconnect(&fileWatcher, &QFileSystemWatcher::directoryChanged,
                        this, MainWindow::on_dirctoryChanged);
    QObject::disconnect(&fileWatcher, &QFileSystemWatcher::fileChanged,
                        this, MainWindow::on_fileChanged);
}

你可能感兴趣的:(QT,qt)