Qt learning notes -- file reading and writing (QFile, QDataStream, QTextStream)

I. QFile

Head file:

#include<QFile>
#include<QFileDialog>

QFile read file

basic operation

Open file dialog box with button

void Widget::on_pushButton_clicked()
{
    QString path =QFileDialog::getOpenFileName(this,"open","../","TXT(*.txt)");
    if(path.isEmpty()==false)
    {
        //File object
        QFile file(path);

        //Open file, read-only mode
        bool isOk=file.open(QIODevice::ReadOnly);
        if(isOk==true)
        {
            //Read file only utf8 encoding by default
            QByteArray arr=file.readAll();
            //Show to edit area
            //ui->textEdit->setText(QString(arr));
            ui->textEdit->setText(arr);

        }
        //Close file
        file.close();
    }
}

Why use the QByteArray class here, because it is the return value of the readall function that determines

Read all remaining data from the device and return it as a byte array.
The function does not have a method to report an error; returning an empty QByteArray may mean that there is currently no data to read, or an error has occurred.

About QByteArray:
The QByteArray class provides a byte array.
QByteArray can be used to store original bytes (including '\ 0') and traditional 8-bit '\ 0' terminated strings. QByteArray is much easier to use than const char *. In the background, it always ensures that the data is followed by a '\ 0' terminator, and uses implicit sharing (copy on write) to reduce memory usage and avoid unnecessary data replication.

Be careful

There
//Read file default UFT-8 encoding
QByteArray arr=file.readAll();
There will be garbled code when opening the txt file



After saving as UTF-8
Open it again

in addition
There is also a way to read files line by line

while(file.atEnd()==false)
            {
                //Read row
                arr +=file.readLine();
            }
            ui->textEdit->setText(arr);

It is also in UTF8 format by default

QFile write file

void Widget::on_pushButton_2_clicked()
{
    QString path=QFileDialog::getSaveFileName(this,"save","../","TXT(*.txt)");
    if(path.isEmpty()==false)
    {
        QFile file;//Create a file object
        file.setFileName(path);

        //Open file, write only
        bool isOk=file.open(QIODevice::WriteOnly);
		
		//Judge whether to open
        if(isOk==true)
        {
            //Get the contents of the editing area
            QString str=ui->textEdit->toPlainText();
            //Writing file
            //Put qstring - > qbytearray
            file.write(str.toUtf8());//Especially for Chinese            
        }

        file.close();
    }

}

According to the write() function

Other conversion methods;

//Convert to local platform encoding
file.write(str.toLocal8Bit());
                      
//QString->c++ string->char*
file.write(str.toStdString().data());

//QString->QByteArray->char*
file.write(str.toUtf8().data());

Save to the Debug file of the current project and name it "test. txt"

2, QDataStream data stream file

Header file

#include<QDataStream>

QDataStream write

void Widget::writeData()
{
    QFile file("../test.txt");

    //Open file
    bool isOk=file.open(QIODevice::WriteOnly);
    if(isOk==true)
    {
        QDataStream stream(&file);

        //Create a file stream and associate it with a file file
        //Entering data into a data stream is equivalent to writing data into a file
        stream<<QString("Saltfish four protuberance")<<250;

    }
        file.close();
}

After the constructor calls read and write
After opening the test.txt file, you will find that the file is garbled. You can convert it to local code through toLocal8Bit()
(but it's more difficult to read again according to the code conversion.)
It doesn't matter what the format is. As long as it can be read through the function

QDataStream read

void Widget::readData()
{
    QFile file("../test.txt");

    //Open file
    bool isOk=file.open(QIODevice::ReadOnly);
    if(isOk==true)
    {
        //Reading data into a data stream is equivalent to reading data into a file
        QDataStream stream(&file);
        //When reading, follow the order of writing
        QString str;
        int a;
        stream>>str>>a;

        qDebug()<<str.toUtf8().data()<<a;//Turn to Chinese

    }
    file.close();

}

3, QTextStream

Header file

#include<QTextStream>

QTextStream write

----------------------------.h----------------------------------
public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    void writeData();
    void readData();

----------------------------.cpp--------------------------------
void Widget::writeData()
{
    QFile file;
    file.setFileName("../demo.txt");

    bool isOk=file.open(QIODevice::WriteOnly);
    if(true==isOk)
    {
        QTextStream stream(&file);
        //Default local code, or specify code
        stream.setCodec("GB18030");

        stream <<QString("Protruding!")<<250;

        file.close();

    }
}

QTextStream read

Do not read the file like QDataStream, because QTextStream does not recognize the type of the read file. The output of QTextStream is just a string, which cannot separate characters and numbers. Therefore, the following methods should be used:

QString path=QFileDialog::getOpenFileName(this,"open","../");
    if(path.isEmpty()==false)
    {
        QFile file;
        file.setFileName(path);

        bool isOk=file.open(QIODevice::ReadOnly);
        if(true==isOk)
        {

            QTextStream stream(&file);
            //Specified encoding
            stream.setCodec("UFT-8");

            QString str=stream.readAll();

            ui->textEdit->setText(str);

            file.close();
        }
    }

4, QFileInfo read file information

Header file

#include<QFileInfo>
Because the return value of created is QDataTime
So also include the header file
Need to output "include < qdebug >

usage

A few simple functions, read more help documents

    //Get file information
        QFileInfo info(path);
        qDebug()<<"File name"<<info.fileName();
        qDebug()<<"file extension"<<info.suffix();
        qDebug()<<"file size"<<info.size();
        qDebug()<<"File creation time"<<info.created().toString("yyyy-MM-dd hh:mm:ss");

Published 5 original articles, praised 0, visited 95
Private letter follow

Tags: encoding

Posted on Thu, 12 Mar 2020 21:20:00 -0700 by anna_cm