当前位置:网站首页>QT -- qfile file read / write operation
QT -- qfile file read / write operation
2022-07-03 19:15:00 【xuechanba】
For reading and writing files ,C and C++ Each has its own way . And in the Qt There is also a set in , That is to use QFile Read and write files .
How to open the file

Read the file
First create a new project , The following operations cater to The embedded Linux Development , Decided to ubuntu In the middle of , And use rsync Remote debugging .
First , Build a scene in the form , And fix the form to the size of the development board screen 1024 * 600 .
The construction steps are as follows : First , Put control LineEdit and PushButton Put in Widget Control , Then click Select Widget Control , Use horizontal alignment , After that, the control TextEdit Drag onto the form ( By stretching , Enlarge the control ), Last , Select the entire form , Use vertical alignment , It becomes as shown in the figure below .
secondly , Want to achieve such a goal : When you click Select file Button , A file dialog box pops up , Then put the selected file path into LineEdit Control , The specific contents of the document are displayed in TextEdit in . My directory is /work/resource/ Two files are prepared in , The content of the file is the same , Use different coding , As shown in the figure below .
Switch to code mainwindow.cpp Come on .
in front , We have introduced the knowledge of file dialog , If you are not clear, you can turn to the front and have a look .
The code is as follows :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Hit the new button , A file dialog box pops up
connect(ui->pushButton,&QPushButton::released,[=](){
// File dialog -- Return the file path of the selected file
QString path = QFileDialog::getOpenFileName(this," Select file ","/home/chantui/work/resourceFile","Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)");
// Put the path into LineEdit Control
// Generally, functions that set text are called setText
ui->lineEdit->setText(path);
// Put the read content into TextEdit Control
QFile file(path);// Parameter is the path to read the file
// Set the opening mode ( Read or write or something else )
file.open(QIODevice::ReadOnly);
// adopt readAll Function can read the contents of the file
// This function returns one QByteArray Value of class type , So you can receive this return value
QByteArray bytearray = file.readAll();
// Put the read data into textEdit in , Also use setText This function
// because setText The parameters required for this function are QString type , Therefore, format conversion is required
// But here, implicit conversion will be performed automatically when compiling , So there is no need for format conversion .
ui->textEdit->setText(bytearray);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
The operation results are as follows :
open utf8 Coded file , give the result as follows :
open ansi Coded file , give the result as follows :
QFile The default support is utf8 Format (Unicode A kind of coding ), and ANSI Format file is GBK code . that QFile Is there no way to read it ? Not at all , Need to use QT A class of encoding format in QTextCodec .
Use QTextCodec This class needs to add header files #include <QTextCodec>
after , Use a static method in this class codecForName , And pass in the file to be read ( character string ) What is the encoding format of .
//codecForName Is a static method in this class , Specify here to "gbk" Code format to read
QTextCodec *codec = QTextCodec::codecForName("gbk");
after , Pass in the path to read the file , Specify how to open , And read the contents of the file .
QFile file(path);// Parameter is the path to read the file
// Set the opening mode ( Read or write or something else )
file.open(QIODevice::ReadOnly);
// adopt readAll Function can read the contents of the file
// This function returns one QByteArray Value of class type , So you can receive this return value
QByteArray bytearray = file.readAll();
Last , It is also a key step , Convert the read file contents into Unicode Coding format ( Need to use toUnicode() This function ), Show it again .
ui->textEdit->setText(codec->toUnicode(bytearray));
Run the code to see :
however , After this conversion , And does not support utf8 The format of the file , Take a look .
therefore , If you want to support at the same time , You need to make a judgment , It happens to be " e-book " In this project , I learned to .^ _ ^
In the previous code , We're going to use readAll() This method reads the text content directly , Now let's introduce another way readAll() — Read by line .
The code is as follows :
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Hit the new button , A file dialog box pops up
connect(ui->pushButton,&QPushButton::released,[=](){
// File dialog -- Return the file path of the selected file
QString path = QFileDialog::getOpenFileName(this," Select file ","/home/chantui/work/resourceFile","Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)");
// Put the path into LineEdit Control
// Generally, functions that set text are called setText
ui->lineEdit->setText(path);
// Put the read content into TextEdit Control
QFile file(path);// Parameter is the path to read the file
// Set the opening mode ( Read or write or something else )
file.open(QIODevice::ReadOnly);
QByteArray array;
// adopt readline The function reads the contents of the file line by line
// adopt atEnd() This method is used to judge whether the end of the file is read
while(!file.atEnd())
{
array += file.readLine();
}
ui->textEdit->setText(array);
});
}
The running result is the same as above ( What I read is utf8 File format ).
It has been forgotten that a very important thing is not to operate on files , To close the file .
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Hit the new button , A file dialog box pops up
connect(ui->pushButton,&QPushButton::released,[=](){
...
...
...
// Close the file object
file.close();
});
}
Write files
If you use write only ( WriteOnly ) To open a file , The contents of the source file will be overwritten . Here we add (Append) To open a file , Write again .
// Set the opening mode ( Open by append , And then write )
file.open(QIODevice::Append);
file.write(" Work hard to prosper the country ");
file.close();
边栏推荐
- Why should the gradient be manually cleared before back propagation in pytorch?
- Simple solution of physical backup and restore of Damon database
- leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
- [mathematical modeling] ship three degree of freedom MMG model based on MATLAB [including Matlab source code 1925]
- 235. Ancêtre public le plus proche de l'arbre de recherche binaire [modèle LCA + même chemin de recherche]
- EGO Planner代码解析bspline_optimizer部分(3)
- Sqlalchemy - subquery in a where clause - Sqlalchemy - subquery in a where clause
- [proteus simulation] a simple encrypted electronic password lock designed with 24C04 and 1602LCD
- Think of new ways
- Le changement est un thème éternel
猜你喜欢

Zhengda futures news: soaring oil prices may continue to push up global inflation
![235. Ancêtre public le plus proche de l'arbre de recherche binaire [modèle LCA + même chemin de recherche]](/img/f5/f2d244e7f19e9ddeebf070a1d06dce.png)
235. Ancêtre public le plus proche de l'arbre de recherche binaire [modèle LCA + même chemin de recherche]

【疾病识别】基于matlab GUI机器视觉肺癌检测系统【含Matlab源码 1922期】

leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】

The earliest record

东数西算拉动千亿产业,敢啃“硬骨头”的存储厂商才更有机会

Sentinel source code analysis part I sentinel overview

Why should we do feature normalization / standardization?

Using the visualization results, click to appear the corresponding sentence

Record: pymysql is used in pycharm to connect to the database
随机推荐
User identity used by startup script and login script in group policy
Analysis of dart JSON encoder and decoder
SQL injection for Web Security (1)
Luogu-p1107 [bjwc2008] Lei Tao's kitten
Differential constrained SPFA
Free year-end report summary template Welfare Collection
Counting from the East and counting from the West will stimulate 100 billion industries. Only storage manufacturers who dare to bite the "hard bone" will have more opportunities
【LeetCode】【SQL】刷题笔记
math_泰勒公式
Flutter network and data storage framework construction-b1
[proteus simulation] a simple encrypted electronic password lock designed with 24C04 and 1602LCD
Next spread
Analyse du Code du planificateur ego bspline Section Optimizer (1)
Record: install MySQL on ubuntu18.04
[wallpaper] (commercially available) 70 wallpaper HD free
Record: writing MySQL commands
Pan for in-depth understanding of the attention mechanism in CV
Record: pymysql is used in pycharm to connect to the database
The online customer service system developed by PHP is fully open source without encryption, and supports wechat customer service docking
The installation path cannot be selected when installing MySQL 8.0.23