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 using 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

1️⃣Set ui interface

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

   //点击选取文件按钮,弹出文件对话框
    connect(ui->pushButton,&QPushButton::clicked,[=](){
    QString path=  QFileDialog::getOpenFileName(this,"打开文件","C:/Users/WFD/Desktop");
   //将路径显示在lineEdit中
   ui->lineEdit->setText(path);

      //读取文件内容,放入textEdit中
      QFile file(path);//参数就是文件的路径
      //设置打开方式
      file.open(QIODevice::ReadOnly);
      //用QByteArray类去接收读取的信息
      QByteArray array=file.readAll();
      //将读取到的数据放入textEdit中
      ui->textEdit->setText(array);
      //关闭文件对象
      file.close();

Note: When setting the opening method

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

QIODevice::ReadOnly  //以只读方式打开文件,用于载入文件。
QIODevice::WriteOnly  //以只写方式打开文件,用于保存文件。
QIODevice::ReadWrite //以读写方式打开。
QIODevice::Append  //以添加模式打开,新写入文件的数据添加到文件尾部。
QIODevice::Truncate //以截取方式打开文件,文件原有的内容全部被删除。
QIODevice::Text       //以文本方式打开文件,读取时“\n”被自动翻译为换行符,写入时字符串结束符会自动翻译为系统平台的编码,如 Windows 平台下是“\r\n”。

这些取值可以组合,例如 QIODevice::ReadOnly | QIODevice::Text 表示以只读和文本方式打开文件。

NOTE: When manipulating files

Open a text file in read-only mode, and then use the readAll() method to read all the contents of the file at once, 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();//+=叠加读过的行
      }

(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

    //点击选取文件按钮,弹出文件对话框
    connect(ui->pushButton,&QPushButton::clicked,[=](){
      QString path=  QFileDialog::getOpenFileName(this,"打开文件","C:/Users/WFD/Desktop");
      //将路径放在lineEdit中
      ui->lineEdit->setText(path);
      //读取文件内容,放入textEdit中
      QFile file(path);//参数就是文件的路径
      //设置打开方式
      file.open(QIODevice::ReadOnly);
      //用QTextStream类去读取文本信息
     QTextStream QS(&file);
     //用QString类去接收读取的信息
     QString array=QS.readAll();
      //将读取到的数据放入textEdit中
      ui->textEdit->setText(array);
      //关闭文件对象
      file.close();

Second, the 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:

Three, file information reading

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.:

expand:

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

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

std::string -> char *        string.date();
  • Commonly used static functions
QFileDialog::getOpenFileName()    //获取指定文件路径名返回QString
QFileDialog::getExistingDirectory()  //获取指定路径返回QString
QFileDialog::getSaveFileName()    //获取指定保存路径名返回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, and 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] 

参数(键=值)

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);
    //Qt中使用QSettings类读写ini文件
    //QSettings构造函数的第一个参数是ini文件的路径,第二个参数表示针对ini文件,第三个参数可以缺省
    QSettings *configIniWrite = new QSettings("hahaya.ini", QSettings::IniFormat);
    //向ini文件中写入内容,setValue函数的两个参数是键值对
    //向ini文件的第一个节写入内容,ip节下的第一个参数
    configIniWrite->setValue("/ip/first", "192.168.0.1");
    //向ini文件的第一个节写入内容,ip节下的第二个参数
    configIniWrite->setValue("ip/second", "127.0.0.1");
    //向ini文件的第二个节写入内容,port节下的第一个参数
    configIniWrite->setValue("port/open", "2222");
    //写入完成后删除指针
    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);
      //将读取到的ini文件保存在QString中,先取值,然后通过toString()函数转换成QString类型
      QString ipResult = configIniRead->value("/ip/second").toString();
      QString portResult = configIniRead->value("/port/open").toString();
      //打印得到的结果
      qDebug() << ipResult;
      qDebug() << portResult;
      //读入入完成后删除指针
      delete configIniRead;
      return a.exec();
}

Guess you like

Origin blog.csdn.net/QtCompany/article/details/130691341