Qt – file read and write operations

Introduction

File reading and writing is a function of many applications, and even some applications are developed around the processing of files in a certain format, so file reading and writing is a basic function of application development.

Qt provides two basic methods for reading and writing plain text files:

  1. Use the IODevice read and write functions of the QFile class to read and write directly
  2. Use the combination of QFile and QTextStream to read and write files with the Stream method.

1. File read operation

(1) Use the QFile class

Qt encapsulates the QFile class, which is convenient for us to operate on files. We can follow the steps below:

  • Use QFile to load file objects
  • Open the file file.open(open method)
  • operation file
  • Close the file file.close()

Example: Click the read and write file button to read the file content into textEdit

1Set ui interface

2 Edit the code in widget.cpp (the QFileDialog class is to open the file)

 //Click the select file button to pop up a file dialog box
    connect(ui->pushButton, & amp; QPushButton::clicked,[=](){
    QString path= QFileDialog::getOpenFileName(this,"Open File","C:/Users/WFD/Desktop");
   //Display the path in lineEdit
   ui->lineEdit->setText(path);

      //Read the content of the file and put it in textEdit
      QFile file(path);//The parameter is the path of the file
      //Set the opening method
      file.open(QIODevice::ReadOnly);
      //Use the QByteArray class to receive the read information
      QByteArray array=file. readAll();
      //Put the read data into textEdit
      ui->textEdit->setText(array);
      //Close the file object
      file. close();

Note: When setting the opening method

When the QFile::open() function opens a file, it needs to pass a parameter of the QIODevice::OpenModeFlag enumeration type to determine how the file is opened. The main values of the QIODevice::OpenModeFlag type are as follows:

QIODevice::ReadOnly //Open the file in read-only mode for loading files.
QIODevice::WriteOnly //Open the file in write-only mode for saving the file.
QIODevice::ReadWrite //Open for reading and writing.
QIODevice::Append //Open in append mode, the data newly written to the file is added to the end of the file.
QIODevice::Truncate //Open the file in the interception mode, and all the original contents of the file will be deleted.
QIODevice::Text //Open the file in text mode, "\\
" is automatically translated into a newline character when reading, and the string end character is automatically translated into the encoding of the system platform when writing, such as "\
" under the Windows platform \r\\
".

These values can be combined, such as QIODevice::ReadOnly | QIODevice::Text means to open the file in read-only and text mode. 

Note: When working with files

Open a text file in read-only mode, and then use the readAll() method to read all the contents of the file at one time, and the return value is a byte array QByteArray. QByteArray is used to store binary data, if you want to read text content, you need to convert it to QString. (Sometimes the system will automatically convert)

We can also use the readLine method to read one line at a time, and then operate on one line of text each time: (use file.atEnd to judge whether the last line is read)

 QByteArray array;
      while(!file.atEnd())
      {
           array + =file.readLine();// + = overlay the read line
      }

(2) Use the QTextStream class

If the operation is a text file, Qt also specially encapsulates a class that handles the text stream, we can use it to read the text content

 //Click the select file button to pop up a file dialog box
    connect(ui->pushButton, & amp; QPushButton::clicked,[=](){
      QString path= QFileDialog::getOpenFileName(this,"Open File","C:/Users/WFD/Desktop");
      // put the path in lineEdit
      ui->lineEdit->setText(path);
      //Read the content of the file and put it in textEdit
      QFile file(path);//The parameter is the path of the file
      //Set the opening method
      file.open(QIODevice::ReadOnly);
      //Use the QTextStream class to read text information
     QTextStream QS( & amp;file);
     //Use the QString class to receive the read information
     QString array=QS. readAll();
      //Put the read data into textEdit
      ui->textEdit->setText(array);
      //Close the file object
      file. close();

Second, file write operation

(1) Use the QFile class

You can also write to files using QFile:

(2) Use the QTextStream class

The QTextStream class overloads operators, and we can stream strings into text files through the << operator:

Third, read file information

In addition to reading and writing operations on files, Qt also encapsulates the QFileInfo class to help us obtain file metadata, such as file size, suffix name, creation time, last modification time, etc.:

Expansion:

  • Each encoding conversion
QString -> QByteArray QString.toUtf8();

QByteArray -> std::string QByteArray.toStdString();

std::string -> char * string. date();
  • Common static functions
QFileDialog::getOpenFileName() //Get the specified file path name and return QString
QFileDialog::getExistingDirectory() //Get the specified path and return QString
QFileDialog::getSaveFileName() //Get the specified save path name and return QString

QT configuration ini file creation, reading and writing operations

1 ini file introduction

The .ini file is an acronym for Initialization File, that is, an initialization file.

In addition to windows, the application software under many other operating systems also has .ini files, which are used to configure the application software to meet the requirements of different users. Generally, there is no need to directly edit these .ini files, the graphical interface of the application can be operated to achieve the same function. It can be used to store software information, registry information, etc.

2 ini file format

INI files consist of sections, keys, and values.

 section

[section]

parameter (key=value)

name=value

The following is an example of an ini file

[Section1 Name]

KeyName1=value1

KeyName2=value2

...

[Section2 Name]

KeyName21=value21

KeyName22=value22 

Among them: [Section1 Name] is used to represent a paragraph. Because the INI file may be shared by the project, the [Section Name] section name is used to distinguish the parameter areas for different purposes. For example: [Section1 Name] indicates the sensor sensitivity parameter area; [Section2 Name] indicates the measurement channel parameter area and so on.

Note: use a semicolon (;). The text after the semicolon, up to the end of the line, is all comments.

3 Qt write ini file

#include <QApplication>
#include <QSettings>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //Use the QSettings class to read and write ini files in Qt
    //The first parameter of the QSettings constructor is the path of the ini file, the second parameter indicates the ini file, and the third parameter can be default
    QSettings *configIniWrite = new QSettings("hahaya.ini", QSettings::IniFormat);
    //Write content to the ini file, the two parameters of the setValue function are key-value pairs
    //Write content to the first section of the ini file, the first parameter under the ip section
    configIniWrite->setValue("/ip/first", "192.168.0.1");
    //Write content to the first section of the ini file, the second parameter under the ip section
    configIniWrite->setValue("ip/second", "127.0.0.1");
    //Write content to the second section of the ini file, the first parameter under the port section
    configIniWrite->setValue("port/open", "2222");
    //Delete the pointer after writing
    delete configIniWrite;
    return a.exec();
}

After running the program, open the hahaya.ini file in the program directory, the result is as shown in the figure below:

4 Qt read ini file

#include <QApplication>
#include <QSettings>
#include<QDebug>
int main(int argc, char *argv[])
{
      QApplication a(argc, argv);
      QSettings *configIniRead = new QSettings("hahaya.ini", QSettings::IniFormat);
      //Save the read ini file in QString, get the value first, and then convert it to QString type through the toString() function
      QString ipResult = configIniRead->value("/ip/second").toString();
      QString portResult = configIniRead->value("/port/open").toString();
      // print the result
      qDebug() << ipResult;
      qDebug() << portResult;
      //Delete the pointer after reading in
      delete configIniRead;
      return a.exec();
}