Qt file system source code analysis - the sixth QSaveFile

depth

This article mainly analyzes the Windows platform, and Mac and Linux are not involved for the time being

This article only analyzes the Win32 API/Windows Com component/STL library function level, and does not explore the lower-level code

This article QT version 5.15.2

class diagram

QTemporaryFile inherits QFile

QFile、QSaveFile继承QFileDevice

QFileDevice inherits QIODevice

QIODevice, QFileSystemWatcher inherit QObject

QLockFile, QFileInfo, QDir, QFileSelector have no inheritance relationship

There is a QObjectData pointer d_ptr in QObject. d_ptr is a protected member variable, which means that each subclass can modify d_ptr content. In QObject d_ptr points to QObjectPrivate,

d_ptr in QIODevice points to QIODevicePrivate

d_ptr in QFileDevice points to QFileDevicePrivate

d_ptr in QFile points to QFilePrivate

d_ptr-oriented QTemporaryFilePrivate in QTemporaryFile

QFileInfo, QDir, and QLockFile do not inherit QObject, so there is no pointer d_ptr pointing to QObjectData. But each also declares that the d_ptr variable points to its own private class

d_ptr in QFileInfo points to QFileInfoPrivate

d_ptr in QDir points to QDirPrivate

d_ptr in QLockFile points to QLockFilePrivate

Inspiration:

This Private class writing method is suitable for scenarios where the exported interface is stable, the internal implementation details are not disclosed, and the internals can be modified flexibly

It can be used in usage scenarios such as paid plug-ins and software reverse engineering

QSaveFile

effect

Provides an interface for securely writing files. Regardless of whether the program crashes or the power is cut off when the program is writing the file, the target file must be complete, either the file before modification or the file after modification, and there will be no data disorder.

principle

When writing, write to the temporary file first, and replace the target file with the temporary file after the writing is completed

Example of use

#include <QSaveFile>

#include <QByteArray>

int main(int argc, char* argv[])

{

QSaveFile file("D:/1.txt");

if (file.open(QIODevice::WriteOnly))

{

file.write("Hello QFile!");

}

file.commit();

return 0;

}

Main function call process and principle

QSaveFile::open

open a file

QSaveFile::commit

Submit the modified content. In fact, it is to let the temporary file replace the target file

write to the end

For now, I will write this first. No matter what opinions or suggestions you have, you can write them in the comment area and discuss them together.

Guess you like

Origin blog.csdn.net/sinat_36391009/article/details/130902335