当前位置:网站首页>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();
边栏推荐
- FBI警告:有人利用AI换脸冒充他人身份进行远程面试
- How can I avoid "div/0!" Errors in Google Docs spreadsheet- How do I avoid the '#DIV/0!' error in Google docs spreadsheet?
- EGO Planner代碼解析bspline_optimizer部分(1)
- math_ Taylor formula
- Day18 - basis of interface testing
- A green plug-in that allows you to stay focused, live and work hard
- Today I am filled with emotion
- The installation path cannot be selected when installing MySQL 8.0.23
- Common PostgreSQL commands
- Find the median of two positive arrays
猜你喜欢
[optics] vortex generation based on MATLAB [including Matlab source code 1927]
SSM整合-前后台协议联调(列表功能、添加功能、添加功能状态处理、修改功能、删除功能)
FBI警告:有人利用AI换脸冒充他人身份进行远程面试
User identity used by startup script and login script in group policy
Dart JSON编码器和解码器剖析
Why should we do feature normalization / standardization?
PyTorch中在反向传播前为什么要手动将梯度清零?
Help change the socket position of PCB part
SQL custom collation
SQL injection for Web Security (1)
随机推荐
ActiveMQ的基础
Web Security (VIII) what is CSRF attack? Why can token prevent csdf attacks?
[new year job hopping season] test the technical summary of interviewers' favorite questions (with video tutorials and interview questions)
Floating source code comment (38) parallel job processor
How does if ($variable) work? [repeat] - how exactly does if ($variable) work? [duplicate]
我眼中真正优秀的CTO长啥样
Go home early today
2022.02.11
Record the errors reported when running fluent in the simulator
變化是永恒的主題
Latex image rotates with title
[disease identification] machine vision lung cancer detection system based on Matlab GUI [including Matlab source code 1922]
Flutter网络和数据存储框架搭建 -b1
Record: pymysql is used in pycharm to connect to the database
【数学建模】基于matlab船舶三自由度MMG模型【含Matlab源码 1925期】
Record: MySQL changes the time zone
【Proteus仿真】用24C04与1602LCD设计的简易加密电子密码锁
Sqlalchemy - subquery in a where clause - Sqlalchemy - subquery in a where clause
EGO Planner代碼解析bspline_optimizer部分(1)
达梦数据库的物理备份和还原简解