当前位置:网站首页>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();
边栏推荐
- Simple solution of physical backup and restore of Damon database
- Smart wax therapy machine based on STM32 and smart cloud
- Using the visualization results, click to appear the corresponding sentence
- Random numbers in a long range, is that right- Random number in long range, is this the way?
- Ego planner code parsing Bspline_ Optimizer section (1)
- shell 脚本中关于用户输入参数的处理
- Record the errors reported when running fluent in the simulator
- [wallpaper] (commercially available) 70 wallpaper HD free
- Record: install MySQL on ubuntu18.04
- Free hand account sharing in September - [cream Nebula]
猜你喜欢

Record: pymysql is used in pycharm to connect to the database

Record: install MySQL on ubuntu18.04

FBI warning: some people use AI to disguise themselves as others for remote interview

FBI warning: some people use AI to disguise themselves as others for remote interview

【光学】基于matlab涡旋光产生【含Matlab源码 1927期】

平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方

【LeetCode】【SQL】刷题笔记

Valentine's Day - make an exclusive digital collection for your lover

【光学】基于matlab介电常数计算【含Matlab源码 1926期】

Flutter network and data storage framework construction-b1
随机推荐
Help change the socket position of PCB part
Does SQL always report foreign key errors when creating tables?
EGO Planner代码解析bspline_optimizer部分(3)
SQL injection for Web Security (1)
math_泰勒公式
Valentine's Day - make an exclusive digital collection for your lover
We have built an intelligent retail settlement platform
Pytorch introduction to deep learning practice notes 13- advanced chapter of cyclic neural network - Classification
2022.02.11
leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】
HOW TO WRITE A DAILY LAB NOTE?
How to design a high concurrency system
PyTorch中在反向传播前为什么要手动将梯度清零?
Le changement est un thème éternel
Ego planner code parsing Bspline_ Optimizer section (1)
Sentinel source code analysis part I sentinel overview
[leetcode] [SQL] notes
【数学建模】基于matlab船舶三自由度MMG模型【含Matlab源码 1925期】
【Proteus仿真】用24C04与1602LCD设计的简易加密电子密码锁
A green plug-in that allows you to stay focused, live and work hard