当前位置:网站首页>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();
边栏推荐
- These problems should be paid attention to in the production of enterprise promotional videos
- Simulation scheduling problem of SystemVerilog (1)
- Streaming media server (16) -- figure out the difference between live broadcast and on-demand
- 2022.02.11
- [disease identification] machine vision lung cancer detection system based on Matlab GUI [including Matlab source code 1922]
- OSPF - detailed explanation of stub area and full stub area
- __ Weak and__ The difference between blocks
- Free sharing | linefriends hand account inner page | horizontal grid | not for sale
- C enum contains value - C enum contains value
- leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】
猜你喜欢
Recommend a GIF processing artifact less than 300K - gifsicle (free download)
Ego planner code parsing Bspline_ Optimizer section (3)
Simulation scheduling problem of SystemVerilog (1)
How to build an efficient information warehouse
leetcode:556. Next larger element III [simulation + change as little as possible]
Know what it is, and know why, JS object creation and inheritance [summary and sorting]
Sentinel source code analysis part II - sentinel dashboard console startup and configuration
记录在模拟器中运行flutter时报的错
2022.02.11
ActiveMQ的基础
随机推荐
Record: MySQL changes the time zone
01. Preparation for automated office (free guidance, only three steps)
TFs and SVN [closed] - TFs vs SVN [closed]
Smart wax therapy machine based on STM32 and smart cloud
leetcode:11. 盛最多水的容器【雙指針 + 貪心 + 去除最短板】
SQL injection for Web Security (1)
Think of new ways
Go home early today
Bad mentality leads to different results
High concurrency Architecture - distributed search engine (ES)
Free year-end report summary template Welfare Collection
【光学】基于matlab介电常数计算【含Matlab源码 1926期】
A green plug-in that allows you to stay focused, live and work hard
Common PostgreSQL commands
Php based campus lost and found platform (automatic matching push)
Which do MySQL and Oracle learn?
达梦数据库的物理备份和还原简解
Ego planner code parsing Bspline_ Optimizer section (2)
Flask generates swagger documents
Find the median of two positive arrays