![]() |
Qt 6.x
The Qt SDK
|
\inmodule QtCore More...
#include <qsavefile.h>
Public Member Functions | |
QSaveFile (const QString &name) | |
Constructs a new file object to represent the file with the given name. | |
QSaveFile (QObject *parent=nullptr) | |
Constructs a new file object with the given parent. | |
QSaveFile (const QString &name, QObject *parent) | |
Constructs a new file object with the given parent to represent the file with the specified name. | |
~QSaveFile () | |
Destroys the file object, discarding the saved contents unless commit() was called. | |
QString | fileName () const override |
Returns the name set by setFileName() or to the QSaveFile constructor. | |
void | setFileName (const QString &name) |
Sets the name of the file. | |
bool | open (OpenMode flags) override |
Opens the file using OpenMode mode, returning true if successful; otherwise false. | |
bool | commit () |
Commits the changes to disk, if all previous writes were successful. | |
void | cancelWriting () |
Cancels writing the new file. | |
void | setDirectWriteFallback (bool enabled) |
Allows writing over the existing file if necessary. | |
bool | directWriteFallback () const |
Returns true if the fallback solution for saving files in read-only directories is enabled. | |
![]() | |
~QFileDevice () | |
Destroys the file device, closing it if necessary. | |
FileError | error () const |
Returns the file error status. | |
void | unsetError () |
Sets the file's error to QFileDevice::NoError. | |
void | close () override |
Calls QFileDevice::flush() and closes the file. | |
bool | isSequential () const override |
Returns true if the file can only be manipulated sequentially; otherwise returns false . | |
int | handle () const |
Returns the file handle of the file. | |
virtual QString | fileName () const |
Returns the name of the file. | |
qint64 | pos () const override |
\reimp | |
bool | seek (qint64 offset) override |
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. | |
bool | atEnd () const override |
Returns true if the end of the file has been reached; otherwise returns false. | |
bool | flush () |
Flushes any buffered data to the file. | |
qint64 | size () const override |
Returns the size of the file. | |
virtual bool | resize (qint64 sz) |
Sets the file size (in bytes) sz. | |
virtual Permissions | permissions () const |
Returns the complete OR-ed together combination of QFile::Permission for the file. | |
virtual bool | setPermissions (Permissions permissionSpec) |
Sets the permissions for the file to the permissions specified. | |
uchar * | map (qint64 offset, qint64 size, MemoryMapFlags flags=NoOptions) |
Maps size bytes of the file into memory starting at offset. | |
bool | unmap (uchar *address) |
Unmaps the memory address. | |
QDateTime | fileTime (QFileDevice::FileTime time) const |
bool | setFileTime (const QDateTime &newDate, QFileDevice::FileTime fileTime) |
![]() | |
QIODevice () | |
Constructs a QIODevice object. | |
QIODevice (QObject *parent) | |
Constructs a QIODevice object with the given parent. | |
virtual | ~QIODevice () |
The destructor is virtual, and QIODevice is an abstract base class. | |
QIODeviceBase::OpenMode | openMode () const |
Returns the mode in which the device has been opened; i.e. | |
void | setTextModeEnabled (bool enabled) |
If enabled is true, this function sets the \l Text flag on the device; otherwise the \l Text flag is removed. | |
bool | isTextModeEnabled () const |
Returns true if the \l Text flag is enabled; otherwise returns false . | |
bool | isOpen () const |
Returns true if the device is open; otherwise returns false . | |
bool | isReadable () const |
Returns true if data can be read from the device; otherwise returns false. | |
bool | isWritable () const |
Returns true if data can be written to the device; otherwise returns false. | |
virtual bool | isSequential () const |
Returns true if this device is sequential; otherwise returns false. | |
int | readChannelCount () const |
int | writeChannelCount () const |
int | currentReadChannel () const |
void | setCurrentReadChannel (int channel) |
int | currentWriteChannel () const |
void | setCurrentWriteChannel (int channel) |
virtual bool | open (QIODeviceBase::OpenMode mode) |
Opens the device and sets its OpenMode to mode. | |
virtual void | close () |
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen. | |
virtual qint64 | pos () const |
For random-access devices, this function returns the position that data is written to or read from. | |
virtual qint64 | size () const |
For open random-access devices, this function returns the size of the device. | |
virtual bool | seek (qint64 pos) |
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. | |
virtual bool | atEnd () const |
Returns true if the current read and write position is at the end of the device (i.e. | |
virtual bool | reset () |
Seeks to the start of input for random-access devices. | |
virtual qint64 | bytesAvailable () const |
Returns the number of bytes that are available for reading. | |
virtual qint64 | bytesToWrite () const |
For buffered devices, this function returns the number of bytes waiting to be written. | |
qint64 | read (char *data, qint64 maxlen) |
Reads at most maxSize bytes from the device into data, and returns the number of bytes read. | |
QByteArray | read (qint64 maxlen) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. | |
QByteArray | readAll () |
Reads all remaining data from the device, and returns it as a byte array. | |
qint64 | readLine (char *data, qint64 maxlen) |
This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. | |
QByteArray | readLine (qint64 maxlen=0) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Reads a line from the device, but no more than maxSize characters, and returns the result as a byte array. | |
virtual bool | canReadLine () const |
Returns true if a complete line of data can be read from the device; otherwise returns false . | |
void | startTransaction () |
void | commitTransaction () |
void | rollbackTransaction () |
bool | isTransactionStarted () const |
qint64 | write (const char *data, qint64 len) |
Writes at most maxSize bytes of data from data to the device. | |
qint64 | write (const char *data) |
qint64 | write (const QByteArray &data) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Writes the content of data to the device. | |
qint64 | peek (char *data, qint64 maxlen) |
QByteArray | peek (qint64 maxlen) |
qint64 | skip (qint64 maxSize) |
virtual bool | waitForReadyRead (int msecs) |
Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. | |
virtual bool | waitForBytesWritten (int msecs) |
For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. | |
void | ungetChar (char c) |
Puts the character c back into the device, and decrements the current position unless the position is 0. | |
bool | putChar (char c) |
Writes the character c to the device. | |
bool | getChar (char *c) |
Reads one character from the device and stores it in c. | |
QString | errorString () const |
Returns a human-readable description of the last device error that occurred. | |
![]() | |
Q_INVOKABLE | QObject (QObject *parent=nullptr) |
Constructs an object with parent object parent. | |
virtual | ~QObject () |
Destroys the object, deleting all its child objects. | |
virtual bool | event (QEvent *event) |
This virtual function receives events to an object and should return true if the event e was recognized and processed. | |
virtual bool | eventFilter (QObject *watched, QEvent *event) |
Filters events if this object has been installed as an event filter for the watched object. | |
QString | objectName () const |
Q_WEAK_OVERLOAD void | setObjectName (const QString &name) |
Sets the object's name to name. | |
void | setObjectName (QAnyStringView name) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
QBindable< QString > | bindableObjectName () |
bool | isWidgetType () const |
Returns true if the object is a widget; otherwise returns false . | |
bool | isWindowType () const |
Returns true if the object is a window; otherwise returns false . | |
bool | isQuickItemType () const |
Returns true if the object is a QQuickItem; otherwise returns false . | |
bool | signalsBlocked () const noexcept |
Returns true if signals are blocked; otherwise returns false . | |
bool | blockSignals (bool b) noexcept |
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). | |
QThread * | thread () const |
Returns the thread in which the object lives. | |
void | moveToThread (QThread *thread) |
Changes the thread affinity for this object and its children. | |
int | startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer) |
This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds. | |
int | startTimer (std::chrono::milliseconds time, Qt::TimerType timerType=Qt::CoarseTimer) |
void | killTimer (int id) |
Kills the timer with timer identifier, id. | |
template<typename T > | |
T | findChild (const QString &aName=QString(), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object. | |
template<typename T > | |
QList< T > | findChildren (const QString &aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. | |
template<typename T > | |
QList< T > | findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
const QObjectList & | children () const |
Returns a list of child objects. | |
void | setParent (QObject *parent) |
Makes the object a child of parent. | |
void | installEventFilter (QObject *filterObj) |
Installs an event filter filterObj on this object. | |
void | removeEventFilter (QObject *obj) |
Removes an event filter object obj from this object. | |
QMetaObject::Connection | connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const |
bool | disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const |
bool | disconnect (const QObject *receiver, const char *member=nullptr) const |
void | dumpObjectTree () const |
Dumps a tree of children to the debug output. | |
void | dumpObjectInfo () const |
Dumps information about signal connections, etc. | |
bool | setProperty (const char *name, const QVariant &value) |
Sets the value of the object's name property to value. | |
bool | setProperty (const char *name, QVariant &&value) |
QVariant | property (const char *name) const |
Returns the value of the object's name property. | |
QList< QByteArray > | dynamicPropertyNames () const |
QBindingStorage * | bindingStorage () |
const QBindingStorage * | bindingStorage () const |
QObject * | parent () const |
Returns a pointer to the parent object. | |
bool | inherits (const char *classname) const |
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false . | |
Protected Member Functions | |
qint64 | writeData (const char *data, qint64 len) override |
\reimp | |
![]() | |
QFileDevice () | |
QFileDevice (QObject *parent) | |
QFileDevice (QFileDevicePrivate &dd, QObject *parent=nullptr) | |
qint64 | readData (char *data, qint64 maxlen) override |
\reimp | |
qint64 | writeData (const char *data, qint64 len) override |
\reimp | |
qint64 | readLineData (char *data, qint64 maxlen) override |
\reimp | |
![]() | |
QIODevice (QIODevicePrivate &dd, QObject *parent=nullptr) | |
virtual qint64 | readData (char *data, qint64 maxlen)=0 |
Reads up to maxSize bytes from the device into data, and returns the number of bytes read or -1 if an error occurred. | |
virtual qint64 | readLineData (char *data, qint64 maxlen) |
Reads up to maxSize characters into data and returns the number of characters read. | |
virtual qint64 | skipData (qint64 maxSize) |
virtual qint64 | writeData (const char *data, qint64 len)=0 |
Writes up to maxSize bytes from data to the device. | |
void | setOpenMode (QIODeviceBase::OpenMode openMode) |
Sets the OpenMode of the device to openMode. | |
void | setErrorString (const QString &errorString) |
Sets the human readable description of the last device error that occurred to str. | |
![]() | |
QObject * | sender () const |
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr. | |
int | senderSignalIndex () const |
int | receivers (const char *signal) const |
Returns the number of receivers connected to the signal. | |
bool | isSignalConnected (const QMetaMethod &signal) const |
virtual void | timerEvent (QTimerEvent *event) |
This event handler can be reimplemented in a subclass to receive timer events for the object. | |
virtual void | childEvent (QChildEvent *event) |
This event handler can be reimplemented in a subclass to receive child events. | |
virtual void | customEvent (QEvent *event) |
This event handler can be reimplemented in a subclass to receive custom events. | |
virtual void | connectNotify (const QMetaMethod &signal) |
virtual void | disconnectNotify (const QMetaMethod &signal) |
QObject (QObjectPrivate &dd, QObject *parent=nullptr) | |
![]() | |
~QIODeviceBase ()=default | |
Private Member Functions | |
void | close () override |
\reimp This method has been made private so that it cannot be called, in order to prevent mistakes. | |
Additional Inherited Members | |
![]() | |
enum | FileError { NoError = 0 , ReadError = 1 , WriteError = 2 , FatalError = 3 , ResourceError = 4 , OpenError = 5 , AbortError = 6 , TimeOutError = 7 , UnspecifiedError = 8 , RemoveError = 9 , RenameError = 10 , PositionError = 11 , ResizeError = 12 , PermissionsError = 13 , CopyError = 14 } |
This enum describes the errors that may be returned by the error() function. More... | |
enum | FileTime { FileAccessTime , FileBirthTime , FileMetadataChangeTime , FileModificationTime } |
enum | Permission { ReadOwner = 0x4000 , WriteOwner = 0x2000 , ExeOwner = 0x1000 , ReadUser = 0x0400 , WriteUser = 0x0200 , ExeUser = 0x0100 , ReadGroup = 0x0040 , WriteGroup = 0x0020 , ExeGroup = 0x0010 , ReadOther = 0x0004 , WriteOther = 0x0002 , ExeOther = 0x0001 } |
This enum is used by the permission() function to report the permissions and ownership of a file. More... | |
enum | FileHandleFlag { AutoCloseHandle = 0x0001 , DontCloseHandle = 0 } |
This enum is used when opening a file to specify additional options which only apply to files and not to a generic QIODevice. More... | |
enum | MemoryMapFlag { NoOptions = 0 , MapPrivateOption = 0x0001 } |
![]() | |
enum | OpenModeFlag { NotOpen = 0x0000 , ReadOnly = 0x0001 , WriteOnly = 0x0002 , ReadWrite = ReadOnly | WriteOnly , Append = 0x0004 , Truncate = 0x0008 , Text = 0x0010 , Unbuffered = 0x0020 , NewOnly = 0x0040 , ExistingOnly = 0x0080 } |
This enum is used with QIODevice::open() to describe the mode in which a device is opened. More... | |
![]() | |
void | deleteLater () |
\threadsafe | |
![]() | |
void | readyRead () |
This signal is emitted once every time new data is available for reading from the device's current read channel. | |
void | channelReadyRead (int channel) |
void | bytesWritten (qint64 bytes) |
This signal is emitted every time a payload of data has been written to the device's current write channel. | |
void | channelBytesWritten (int channel, qint64 bytes) |
void | aboutToClose () |
This signal is emitted when the device is about to close. | |
void | readChannelFinished () |
![]() | |
void | destroyed (QObject *=nullptr) |
This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked. | |
void | objectNameChanged (const QString &objectName, QPrivateSignal) |
This signal is emitted after the object's name has been changed. | |
![]() | |
static QMetaObject::Connection | connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection) |
\threadsafe | |
static QMetaObject::Connection | connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection) |
template<typename Func1 , typename Func2 > | |
static QMetaObject::Connection | connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection) |
template<typename Func1 , typename Func2 > | |
static QMetaObject::Connection | connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot) |
static bool | disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member) |
\threadsafe | |
static bool | disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member) |
static bool | disconnect (const QMetaObject::Connection &) |
Disconnect a connection. | |
template<typename Func1 , typename Func2 > | |
static bool | disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot) |
template<typename Func1 > | |
static bool | disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero) |
![]() | |
QScopedPointer< QObjectData > | d_ptr |
![]() | |
QString | objectName |
the name of this object | |
![]() | |
template< class T > T | qobject_cast (const QObject *object) |
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns \nullptr. | |
template< typename T > T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
template< typename T > QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QObjectList | |
\macro Q_CLASSINFO(Name, Value) | |
\inmodule QtCore
The QSaveFile class provides an interface for safely writing to files.
\reentrant
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.
Definition at line 23 of file qsavefile.h.
|
explicit |
Constructs a new file object to represent the file with the given name.
Definition at line 84 of file qsavefile.cpp.
References d.
Constructs a new file object with the given parent.
Definition at line 94 of file qsavefile.cpp.
Constructs a new file object with the given parent to represent the file with the specified name.
Definition at line 102 of file qsavefile.cpp.
References d.
QSaveFile::~QSaveFile | ( | ) |
Destroys the file object, discarding the saved contents unless commit() was called.
Definition at line 113 of file qsavefile.cpp.
References QFileDevice::close(), and d.
void QSaveFile::cancelWriting | ( | ) |
Cancels writing the new file.
If the application changes its mind while saving, it can call cancelWriting(), which sets an error code so that commit() will discard the temporary file.
Alternatively, it can simply make sure not to call commit().
Further write operations are possible after calling this method, but none of it will have any effect, the written file will be discarded.
This method has no effect when direct write fallback is used. This is the case when saving over an existing file in a readonly directory: no temporary file can be created, so the existing file is overwritten no matter what, and cancelWriting() cannot do anything about that, the contents of the existing file will be lost.
Definition at line 342 of file qsavefile.cpp.
References d, QIODevice::isOpen(), and QFileDevice::WriteError.
|
overrideprivatevirtual |
\reimp This method has been made private so that it cannot be called, in order to prevent mistakes.
In order to finish writing the file, call commit(). If instead you want to abort writing, call cancelWriting().
Reimplemented from QFileDevice.
Definition at line 272 of file qsavefile.cpp.
References qFatal.
bool QSaveFile::commit | ( | ) |
Commits the changes to disk, if all previous writes were successful.
It is mandatory to call this at the end of the saving operation, otherwise the file will be discarded.
If an error happened during writing, deletes the temporary file and returns false
. Otherwise, renames it to the final fileName and returns true
on success. Finally, closes the device.
Definition at line 289 of file qsavefile.cpp.
References QFileDevice::close(), d, fileName(), QIODevice::isOpen(), QFileDevice::NoError, Q_ASSERT, qUtf16Printable, and qWarning.
Referenced by QNetworkDiskCachePrivate::storeItem(), and QV4::CompiledData::SaveableUnitPointer::writeDataToFile().
bool QSaveFile::directWriteFallback | ( | ) | const |
Returns true
if the fallback solution for saving files in read-only directories is enabled.
Definition at line 403 of file qsavefile.cpp.
References d.
|
overridevirtual |
Returns the name set by setFileName() or to the QSaveFile constructor.
Reimplemented from QFileDevice.
Definition at line 129 of file qsavefile.cpp.
Referenced by commit(), and open().
|
override |
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Important: the mode must include QIODevice::WriteOnly. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.
QIODevice::ReadWrite, QIODevice::Append, QIODevice::NewOnly and QIODevice::ExistingOnly are not supported at the moment.
Definition at line 157 of file qsavefile.cpp.
References QIODeviceBase::Append, QString::arg(), arg, QAbstractFileEngine::create(), d, QIODeviceBase::ExistingOnly, QFileInfo::exists(), fileName(), QFileInfo::filePath(), initialize(), QFileInfo::isDir(), QIODevice::isOpen(), QFileInfo::isSymLink(), QFileInfo::isWritable(), QIODeviceBase::NewOnly, QFileDevice::NoError, QIODevice::open(), QFileDevice::OpenError, QFileInfo::permissions(), qUtf16Printable, qWarning, QIODeviceBase::ReadOnly, QFileInfo::setFile(), QFileDevice::setPermissions(), QFileInfo::symLinkTarget(), QDir::toNativeSeparators(), QIODeviceBase::Unbuffered, QFileDevice::unsetError(), QFileDevice::UnspecifiedError, QTemporaryFileEngine::Win32NonShared, QFileDevice::WriteError, and QIODeviceBase::WriteOnly.
Referenced by QNetworkDiskCachePrivate::storeItem(), and QV4::CompiledData::SaveableUnitPointer::writeDataToFile().
void QSaveFile::setDirectWriteFallback | ( | bool | enabled | ) |
Allows writing over the existing file if necessary.
QSaveFile creates a temporary file in the same directory as the final file and atomically renames it. However this is not possible if the directory permissions do not allow creating new files. In order to preserve atomicity guarantees, open() fails when it cannot create the temporary file.
In order to allow users to edit files with write permissions in a directory with restricted permissions, call setDirectWriteFallback() with enabled set to true, and the following calls to open() will fallback to opening the existing file directly and writing into it, without the use of a temporary file. This does not have atomicity guarantees, i.e. an application crash or for instance a power failure could lead to a partially-written file on disk. It also means cancelWriting() has no effect, in such a case.
Typically, to save documents edited by the user, call setDirectWriteFallback(true), and to save application internal files (configuration files, data files, ...), keep the default setting which ensures atomicity.
Definition at line 391 of file qsavefile.cpp.
Sets the name of the file.
The name can have no path, a relative path, or an absolute path.
Definition at line 140 of file qsavefile.cpp.
\reimp
Reimplemented from QFileDevice.
Definition at line 354 of file qsavefile.cpp.
References d, QFileDevice::NoError, ret, and QFileDevice::writeData().