Qt input and output devices and file operations

1. Input and output devices

The QIODevice class is the basic interface class of all I/O devices in Qt, and provides an abstract interface for devices that support reading/writing data blocks, such as QFile, QBuffer, and QTcpSocket. The QIODevice class is abstract and cannot be instantiated. Generally, the interface defined by it is used to provide device-independent I/O functions.
Inheritance diagram of the QIODevice class
QIODevice distinguishes between two types of devices: random access devices and sequential storage devices. (You can use the isSequentiaU) function in the program to determine the type of the device. )

  • Random access devices support seeking to arbitrary locations using the seek() function. The current position in the file can be obtained using the pos() function. Such devices include QFile, QBuffer, etc.
  • Sequential storage devices do not support positioning to arbitrary locations, and data must be read at one time. Functions such as Pos() and size()
    cannot be used when operating sequential devices. Such devices include QTcpSocket, QUdpSocket, and QProcess.

file open mode

Before accessing a device, you need to use the open() function to open the device, and you must specify the correct open mode. All open modes in QIODevice are defined by the QIODevice::OPenMode enumeration variable, and its values ​​are listed in the following table, some of which can be used at the same time using the bitwise OR symbol "丨". After opening the device, you can use write() or putChar() to write, use read(), readLine() or readAll() to read, and finally use close() to close the device.
insert image description here
insert image description here

Second, the file QFile

The QFile class provides an interface for reading/writing files, which is an I/O device that can be used to read/write text files, binary files, and Qt resources. QFile can be used alone, or it can be used together with QTextStream or QDataStream, which will be more convenient.
Generally, the file name is specified when constructing the QFile object, of course, it can also be set at any other time using setFileName(). You can use exists() to check whether a file exists, and remove() to delete a file. More advanced operations related to the file system are provided in the QFilelnfo and QDir classes.
A file can be opened with open(), closed with close(), and flushed with flush(). The data reading and writing of files is generally done using QTextStream or QDataStream, but you can also use some functions inherited from the QIODevice class, such as read(), readLine(), readAll() and write(), and only operate one character at a time Functions such as getChar(), putChar(), and ungetChar(). You can use the size() function to obtain the size of the file, use seek() to locate any position in the file, use pos() to obtain the current position, and use atEnd() to determine whether the end of the file has been reached.
(1) Directly use QFile to read and write files.
The sample program is as follows:

//直接使用QFile写文件
QFile fileW("test.txt");
if (!fileW.open(QIODevice::WriteOnly | QIODevice::Text))
	return;
fileW.write("first line!\nsecond line");
fileW.close();

//直接使用QFile读文件
QFile fileR("test.txt");
if (!fileR.open(QIODevice::ReadOnly | QIODevice::Text))
	return;
while (!fileR.atEnd())
{
    
    
	QByteArray line = fileR.readLine();
	qDebug() <<line;
}
fileR.close();

(2) Use text stream to read/write text files
The QTextStream class provides a convenient interface to read/write text, which can be operated on QIODevice, QByteArray and QString. Using QTextStream's stream operators, you can conveniently read/write words, lines and numbers. The sample program is as follows:

//使用QTextStream文本流读文件
QFile fileW("test.txt");
if (!fileW.open(QIODevice::WriteOnly | QIODevice::Text))
	return -1;
QTextStream out(&fileW);
out << "first line" << "\nsecond line";
fileW.close();

//使用QTextStream文本流写文件
QFile fileR("test.txt");
if (!fileR.open(QIODevice::ReadOnly | QIODevice::Text))
	return -1;
QTextStream in(&fileR);
while (!in.atEnd())
{
    
    
	QString line = in.readLine();
	qDebug() <<line;
}

You can use seek() to locate a specified location, and use atEnd() to determine whether there is still data that can be read. If the flush() function is called, QTextStream will clear all data in the write buffer and call the device's flush() function.

Internally, QTextStream uses a Unicode-based buffer, and QTextStream uses QTextCodec to automatically support different character sets. By default, the encoding returned by QTextCodec::codecForLocale() is used for reading and writing, and the setCodec() function can also be used to set the encoding.
(3) Use the data stream to read/write binary data.
The QDataStream class realizes the serialization of the binary data of QIODevice. A data stream is a stream of binary-encoded information, completely independent of the host's operating system, CPU, and byte order. Data streams can also read/write unencoded raw binary data. The QDataStream class can realize the serialization of C++ basic data types, such as char, Short, im and char*, etc. Serializing more complex data is accomplished by decomposing the data into basic data types. The sample program is as follows:

//使用QTextStream文本流读文件
QFile fileW("test.txt");
if (!fileW.open(QIODevice::WriteOnly))
    return -1;
QDataStream out(&fileW);
//串行化字符串(写入时,要求强制转换为QString类型,否则写入的是乱码)
out << QString("the answer is");
//串行化整数
out << static_cast<qint32>(42);
fileW.close();

//使用QTextStream文本流写文件
QFile fileR("test.txt");
if (!fileR.open(QIODevice::ReadOnly))
    return -1;
QDataStream in(&fileR);
QString str;
qint32 num;
in >> str >> num;
qDebug() << str << num; //输出:"the answer is" 42
fileR.close();

Each entry written to the data stream is written using a predefined format, which depends on the type of entry. (Otherwise the writing will be garbled characters) The supported Qt types include QBrush, QColor, QDateTime, QFom, QPixmap, QString, QVariant and many other formats.

3. File information QFilelnfo

The QFilelnfo class provides system-independent file information, including the name of the file, the location (path) in the file system, the access permissions of the file, and whether it is a directory or a symbolic link. QFilelnfo can also get the size of the file and the time of the last modification/read, as well as information about Qt resources. The file pointed to by QFilelnfo can be set when the QFileinfo object is constructed, or later using setFile().

  • QFileInfo can use a relative (relative) path or an absolute (absolute) path to point to a file, and you can also use makeAbsolute() to convert a relative path to an absolute path.
  • The type of the file can be obtained using isFile(), isDir() and isSymLink().
    You can use path() and fileName() to get the path and file name of the file, you can also use baseName() to get the base name in the file name, use suffix() to get the suffix of the file name, use completeSuffix() to get Get the composite suffix.
  • The date of the file can be returned using created(), lastModified() and lastRead();
  • Access rights can be obtained using isReadable(), isWritable() and isExecutable();
  • File ownership can be obtained using owner(), ownerId(), group(), and groupId().

Create a new Qt5 console application named myFile. After the creation is complete, change the content of the main.cpp file to:

#include <QtCore/QCoreApplication>
#include <QFileInfo>
#include <QTextCodec>
#include <QStringList>
#include <QDateTime>
#include <QDebug>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 以只写方式打开,如果文件不存在,那么会创建该文件
    QFile file("myfile.txt");
    if (!file.open(QIODevice::WriteOnly  | QIODevice::Text))
        qDebug() << file.errorString();
    file.write("helloQt!\nyafeilinux");
    file.close();

    // 获取文件信息
    QFileInfo info(file);
    qDebug() << QObject::tr("绝对路径:") << info.absoluteFilePath() << endl
             << QObject::tr("文件名:") << info.fileName() << endl
             << QObject::tr("基本名称:") << info.baseName() << endl
             << QObject::tr("后缀:") << info.suffix() << endl
             << QObject::tr("创建时间:") << info.created() << endl
             << QObject::tr("大小:") << info.size();

    // 以只读方式打开
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << file.errorString();
    qDebug() << QObject::tr("文件内容:") << endl << file.readAll();
    qDebug() << QObject::tr("当前位置:") << file.pos();
    //移动文件开始读取位置为0
    file.seek(0);
    QByteArray array;
    array = file.read(5);
    qDebug() << QObject::tr("前5个字符:") << array
             << QObject::tr("当前位置:") << file.pos();
    //移动文件开始读取位置为15
    file.seek(15);
    array = file.read(5);
    qDebug() << QObject::tr("第16-20个字符:") << array;
    file.close();

    return a.exec();
}

Execute the program, the console output is as follows:

"绝对路径:" "D:/Project/C++/Qt/myFile/build-myFile-Desktop_Qt_5_9_7_MinGW_32bit-Debug/myfile.txt"
"文件名:" "myfile.txt"
"基本名称:" "myfile"
"后缀:" "txt"
"创建时间:" QDateTime(2019-06-17 16:58:01.230 中国标准时间 Qt::TimeSpec(LocalTime))
"大小:" 20
"文件内容:"
"helloQt!\nyafeilinux"
"当前位置:" 20
"前5个字符:" "hello" "当前位置:" 5
"第16-20个字符:" "linux"

Fourth, the temporary file QTemporaryFile

The QTemporaryFile class is an I/O device for manipulating temporary files, which can safely create a unique temporary file. When the open() function is called, a temporary file will be created. The file name of the temporary file can be guaranteed to be unique. When the QTemporaryFile object is destroyed, the file will be automatically deleted.
When calling the open() function, the QIODevice::ReadWrite mode is used by default, and the QTemporaryFile class can be used like the following code:

QTemporaryFile file;
if (file.open()) 
{
    
    
    // 在这里对临时文件进行操作,file.fileName()可以返回唯一的文件名
}

It is safe to reopen the QTemporaryFile after calling the close() function, as long as the QTemporaryFile object is not destroyed, then the only temporary file will always exist and be kept open by QTemporaryFile internally. Temporary files will be generated in the temporary directory of the system by default, and the path of this directory can be obtained by using QDir::tempPath().

Guess you like

Origin blog.csdn.net/houxian1103/article/details/129905227
Recommended