QSaveFile Class

The QSaveFile class provides an interface for safely writing to files. More...

Header: #include <QSaveFile>
qmake: QT += core
Since: Qt 5.1
Inherits: QFileDevice

This class was introduced in Qt 5.1.

Note: All functions in this class are reentrant.

Detailed Description

QSaveFile is an I/O device for writing text and binary files, without losing existing data if the writing operation fails.

While writing, the contents will be written to a temporary file, and if no error happened, commit() will move it to the final file. This ensures that no data at the final file is lost in case an error happens while writing, and no partially-written file is ever present at the final location. Always use QSaveFile when saving entire documents to disk.

QSaveFile automatically detects errors while writing, such as the full partition situation, where write() cannot write all the bytes. It will remember that an error happened, and will discard the temporary file in commit().

Much like with QFile, the file is opened with open(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write().

Unlike QFile, calling close() is not allowed. commit() replaces it. If commit() was not called and the QSaveFile instance is destroyed, the temporary file is discarded.

To abort saving due to an application error, call cancelWriting(), so that even a call to commit() later on will not save.

See also QTextStream, QDataStream, QFileInfo, QDir, QFile, and QTemporaryFile.