Qt Creator module learning-files, directories and input/output (1)

Qt Creator module learning-files, directories and input/output (1)

1. Files and directories

1. Input/Output Devices

The QIODevice class is the basic interface class of all I/0 devices in Qt. For example, QFile, QBuffer, and QTcpSocket provide an abstract interface for devices that support reading/writing data blocks.
In the whole process, we often open the device through the open() function, and must specify the correct open mode. All the open modes in QIODevice are defined by the QIODevice::OpenMode enumeration type. You can find the value by yourself, there are too many...
Let’s just take a few examples

constant description
QIODevice :: NotOpen Device is not turned on
QIODevice::ReadOnly The device is opened as read-only and cannot be written
QIODevice::WriteOnly The device is opened in write-only mode and is not readable
QIODevice::ReadWrite Open for reading and writing
QIODevice::Append Open in append mode (at the end of the file)
QIODevice::Truncate If possible, the device will be truncated before opening, and the previous content of the device will also be lost
QIODevice::Text When reading, the end of line terminator is converted to "/n", when writing, the end of line terminator is converted to local encoding
QIODevice::Unbuffered Bypass all buffers of the device

After writing and reading, close the device through close().
QIODevice can distinguish between devices, into sequential storage devices and random storage devices.
The random storage device can be defined at any position through the seek() function, and the current position can also be obtained with the pos() function. Used for QFile, QBuffer.
The sequential storage device cannot locate any area, and the data must be read once for QTcpStock, QProcess.

The isSequential() function determines the device type in the program.

QTcpStock and QProcess are two big modules, we are now talking about QFile.

2. File operations

The QFile class provides an interface for reading/writing devices. It can read/write text files, binary files and Qt resource I/O devices. QFile can be used alone, but for convenience we often use it in combination with QTextStream/QDataStream.

The QFileInfo class is to provide system-independent file information, such as size, name and location.

#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include <QStringList>
#include <QCoreApplication>
#include <QFileInfo>
#include <QDebug>
#include <QDateTime>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    //以只写方式打开,若文件不存在则创建
    QFile file("file.txt");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
        qDebug()<<file.errorString();
    file.write("hello,Qt \angxn!!");
    file.close();
    QFileInfo info(file);
    qDebug()<<QObject::tr("绝对路径:")<<info.absoluteFilePath()<<endl
            <<QObject::tr("文件名:")<<info.fileName()<<endl
            <<QObject::tr("基本名称:")<<info.baseName()<<endl
            <<QObject::tr("后缀:")<<info.suffix()<<endl
            <<QObject::tr("创建时间:")<<info.created()<<endl
            <<QObject::tr("大小:")<<info.size();
    //以只读方式打开
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
        qDebug()<<file.errorString();
    qDebug()<<QObject::tr("文件内容:")<<endl<<file.readAll();
    qDebug()<<QObject::tr("当前位置:")<<file.pos();
    file.seek(0);
    QByteArray array;
    array = file.read(5);
    qDebug()<<QObject::tr("前五个字符:")<<array
           <<QObject::tr("当前位置:")<<file.pos();
    file.seek(15);
    array = file.read(5);
    qDebug()<<QObject::tr("第16-20个字符")<<array;
    file.close();
    return a.exec();
}

The results are as follows:
Insert picture description here

3. Directory operations

The QDir class is used to access the directory structure and its contents, and can also access the operation path name, access path and file related information.
Let's take an example:
Drag a List Widget into mainwindow.ui and
then add private objects in the .h file:

#include <QFileSystemWatcher>

private:
    QFileSystemWatcher myWatcher;
private slots:
    void showMessage(const QString &path);

main.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);
    connect(&myWatcher,&QFileSystemWatcher::directoryChanged,
            this,&MainWindow::showMessage);
    connect(&myWatcher,&QFileSystemWatcher::fileChanged,
            this,&MainWindow::showMessage);
    //显示当前目录下所有文件
    QDir mydir(QDir::currentPath());
    mydir.setNameFilters(QStringList("*h"));
    ui->listWidget->addItem(mydir.absolutePath()+ tr("目录下的.h文件"));
    ui->listWidget->addItems(mydir.entryList());
    //创建目录加入显示器
    mydir.mkdir("mydir");
    mydir.cd("mydir");
    ui->listWidget->addItem(tr("监视目录:")+mydir.absolutePath());
    myWatcher.addPath(mydir.absolutePath());
    //创建文件加入监视器
    QFile file(mydir.absolutePath()+"/myfile.txt");
    if(file.open(QIODevice::WriteOnly)){
    
    
        QFileInfo info(file);
        ui->listWidget->addItem(tr("监视的文件:")+ info.absolutePath());
        myWatcher.addPath(info.absoluteFilePath());
        file.close();
    }
}

MainWindow::~MainWindow()
{
    
    
    delete ui;
}
void MainWindow::showMessage(const QString &path){
    
    
    QDir dir(QDir::currentPath()+"/mydir");
    //如果目录发生改变
    if(path==dir.absolutePath()){
    
    
        ui->listWidget->addItem(dir.dirName()+tr("目录发生改变:"));
        ui->listWidget->addItems(dir.entryList());
    }
    else{
    
    
        ui->listWidget->addItem(path+tr("文件发生改变"));
    }
}

Everyone can feel for themselves.

Guess you like

Origin blog.csdn.net/m0_50210478/article/details/108143782