KSaveFile

KSaveFile Class Reference

#include <KSaveFile>

Inheritance diagram for KSaveFile:

Public Member Functions

 KSaveFile ()
 
 KSaveFile (const QString &filename)
 
virtual ~KSaveFile ()
 
void abort ()
 
bool directWriteFallback () const
 
QFile::FileError error () const
 
QString errorString () const
 
QString fileName () const override
 
bool finalize ()
 
bool open (OpenMode flags=QIODevice::ReadWrite) override
 
void setDirectWriteFallback (bool enabled)
 
void setFileName (const QString &filename)
 
- Public Member Functions inherited from QFile
 QFile (const QString &name)
 
 QFile (const QString &name, QObject *parent)
 
 QFile (QObject *parent)
 
bool copy (const QString &newName)
 
bool exists () const const
 
bool moveToTrash ()
 
virtual bool open (QIODevice::OpenMode mode) override
 
bool open (FILE *fh, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags)
 
bool open (int fd, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags)
 
virtual QFileDevice::Permissions permissions () const const override
 
bool remove ()
 
bool rename (const QString &newName)
 
virtual bool resize (qint64 sz) override
 
void setFileName (const QString &name)
 
virtual bool setPermissions (QFileDevice::Permissions permissions) override
 
virtual qint64 size () const const override
 
QString symLinkTarget () const const
 
- Public Member Functions inherited from QFileDevice
virtual bool atEnd () const const override
 
virtual void close () override
 
QFileDevice::FileError error () const const
 
QDateTime fileTime (QFileDevice::FileTime time) const const
 
bool flush ()
 
int handle () const const
 
virtual bool isSequential () const const override
 
uchar * map (qint64 offset, qint64 size, QFileDevice::MemoryMapFlags flags)
 
virtual qint64 pos () const const override
 
virtual bool seek (qint64 pos) override
 
bool setFileTime (const QDateTime &newDate, QFileDevice::FileTime fileTime)
 
bool unmap (uchar *address)
 
void unsetError ()
 
- Public Member Functions inherited from QIODevice
 QIODevice (QObject *parent)
 
void aboutToClose ()
 
virtual qint64 bytesAvailable () const const
 
virtual qint64 bytesToWrite () const const
 
void bytesWritten (qint64 bytes)
 
virtual bool canReadLine () const const
 
void channelBytesWritten (int channel, qint64 bytes)
 
void channelReadyRead (int channel)
 
void commitTransaction ()
 
int currentReadChannel () const const
 
int currentWriteChannel () const const
 
QString errorString () const const
 
bool getChar (char *c)
 
bool isOpen () const const
 
bool isReadable () const const
 
bool isTextModeEnabled () const const
 
bool isTransactionStarted () const const
 
bool isWritable () const const
 
QIODevice::OpenMode openMode () const const
 
qint64 peek (char *data, qint64 maxSize)
 
QByteArray peek (qint64 maxSize)
 
bool putChar (char c)
 
qint64 read (char *data, qint64 maxSize)
 
QByteArray read (qint64 maxSize)
 
QByteArray readAll ()
 
int readChannelCount () const const
 
void readChannelFinished ()
 
QByteArray readLine (qint64 maxSize)
 
qint64 readLine (char *data, qint64 maxSize)
 
void readyRead ()
 
virtual bool reset ()
 
void rollbackTransaction ()
 
void setCurrentReadChannel (int channel)
 
void setCurrentWriteChannel (int channel)
 
void setTextModeEnabled (bool enabled)
 
qint64 skip (qint64 maxSize)
 
void startTransaction ()
 
void ungetChar (char c)
 
virtual bool waitForBytesWritten (int msecs)
 
virtual bool waitForReadyRead (int msecs)
 
qint64 write (const char *data)
 
qint64 write (const QByteArray &byteArray)
 
qint64 write (const char *data, qint64 maxSize)
 
int writeChannelCount () const const
 
- Public Member Functions inherited from QObject
 QObject (QObject *parent)
 
bool blockSignals (bool block)
 
const QObjectListchildren () const const
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const const
 
void deleteLater ()
 
void destroyed (QObject *obj)
 
bool disconnect (const char *signal, const QObject *receiver, const char *method) const const
 
bool disconnect (const QObject *receiver, const char *method) const const
 
void dumpObjectInfo ()
 
void dumpObjectInfo () const const
 
void dumpObjectTree ()
 
void dumpObjectTree () const const
 
QList< QByteArraydynamicPropertyNames () const const
 
virtual bool event (QEvent *e)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
findChild (const QString &name, Qt::FindChildOptions options) const const
 
QList< T > findChildren (const QString &name, Qt::FindChildOptions options) const const
 
QList< T > findChildren (const QRegExp &regExp, Qt::FindChildOptions options) const const
 
QList< T > findChildren (const QRegularExpression &re, Qt::FindChildOptions options) const const
 
bool inherits (const char *className) const const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const const
 
bool isWindowType () const const
 
void killTimer (int id)
 
virtual const QMetaObjectmetaObject () const const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const const
 
void objectNameChanged (const QString &objectName)
 
QObjectparent () const const
 
QVariant property (const char *name) const const
 
 Q_CLASSINFO (Name, Value)
 
 Q_DISABLE_COPY (Class)
 
 Q_DISABLE_COPY_MOVE (Class)
 
 Q_DISABLE_MOVE (Class)
 
 Q_EMIT Q_EMIT
 
 Q_ENUM (...)
 
 Q_ENUM_NS (...)
 
 Q_ENUMS (...)
 
 Q_FLAG (...)
 
 Q_FLAG_NS (...)
 
 Q_FLAGS (...)
 
 Q_GADGET Q_GADGET
 
 Q_INTERFACES (...)
 
 Q_INVOKABLE Q_INVOKABLE
 
 Q_NAMESPACE Q_NAMESPACE
 
 Q_NAMESPACE_EXPORT (EXPORT_MACRO)
 
 Q_OBJECT Q_OBJECT
 
 Q_PROPERTY (...)
 
 Q_REVISION Q_REVISION
 
 Q_SET_OBJECT_NAME (Object)
 
 Q_SIGNAL Q_SIGNAL
 
 Q_SIGNALS Q_SIGNALS
 
 Q_SLOT Q_SLOT
 
 Q_SLOTS Q_SLOTS
 
qFindChild (const QObject *obj, const QString &name)
 
QList< T > qFindChildren (const QObject *obj, const QRegExp &regExp)
 
QList< T > qFindChildren (const QObject *obj, const QString &name)
 
qobject_cast (QObject *object)
 
qobject_cast (const QObject *object)
 
 QT_NO_NARROWING_CONVERSIONS_IN_CONNECT QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const char *name, const QVariant &value)
 
bool signalsBlocked () const const
 
int startTimer (int interval, Qt::TimerType timerType)
 
int startTimer (std::chrono::milliseconds time, Qt::TimerType timerType)
 
QThreadthread () const const
 

Additional Inherited Members

- Public Types inherited from QFileDevice
enum  FileError
 
enum  FileHandleFlag
 
enum  FileTime
 
enum  MemoryMapFlags
 
enum  Permission
 
- Public Types inherited from QIODevice
enum  OpenModeFlag
 
- Properties inherited from QObject
 objectName
 
- Static Public Member Functions inherited from QFile
bool copy (const QString &fileName, const QString &newName)
 
QString decodeName (const QByteArray &localFileName)
 
QString decodeName (const char *localFileName)
 
QByteArray encodeName (const QString &fileName)
 
bool exists (const QString &fileName)
 
bool moveToTrash (const QString &fileName, QString *pathInTrash)
 
QFileDevice::Permissions permissions (const QString &fileName)
 
bool remove (const QString &fileName)
 
bool rename (const QString &oldName, const QString &newName)
 
bool resize (const QString &fileName, qint64 sz)
 
void setDecodingFunction (QFile::DecoderFn function)
 
void setEncodingFunction (QFile::EncoderFn function)
 
bool setPermissions (const QString &fileName, QFileDevice::Permissions permissions)
 
QString symLinkTarget (const QString &fileName)
 
- Static Public Member Functions inherited from QObject
QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
 
QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type)
 
QMetaObject::Connection connect (const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
 
QMetaObject::Connection connect (const QObject *sender, PointerToMemberFunction signal, Functor functor)
 
QMetaObject::Connection connect (const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
 
bool disconnect (const QMetaObject::Connection &connection)
 
bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *method)
 
bool disconnect (const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
 
bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method)
 
QString tr (const char *sourceText, const char *disambiguation, int n)
 
QString trUtf8 (const char *sourceText, const char *disambiguation, int n)
 
- Public Attributes inherited from QFile
typedef DecoderFn
 
typedef EncoderFn
 
- Public Attributes inherited from QFileDevice
 AbortError
 
 AutoCloseHandle
 
 CopyError
 
 DontCloseHandle
 
 ExeGroup
 
 ExeOther
 
 ExeOwner
 
 ExeUser
 
 FatalError
 
 FileAccessTime
 
 FileBirthTime
 
typedef FileHandleFlags
 
 FileMetadataChangeTime
 
 FileModificationTime
 
 MapPrivateOption
 
 NoError
 
 NoOptions
 
 OpenError
 
typedef Permissions
 
 PermissionsError
 
 PositionError
 
 ReadError
 
 ReadGroup
 
 ReadOther
 
 ReadOwner
 
 ReadUser
 
 RemoveError
 
 RenameError
 
 ResizeError
 
 ResourceError
 
 TimeOutError
 
 UnspecifiedError
 
 WriteError
 
 WriteGroup
 
 WriteOther
 
 WriteOwner
 
 WriteUser
 
- Public Attributes inherited from QIODevice
 Append
 
 ExistingOnly
 
 NewOnly
 
 NotOpen
 
typedef OpenMode
 
 ReadOnly
 
 ReadWrite
 
 Text
 
 Truncate
 
 Unbuffered
 
 WriteOnly
 
- Public Attributes inherited from QObject
typedef QObjectList
 
- Protected Member Functions inherited from QFileDevice
virtual qint64 readData (char *data, qint64 len) override
 
virtual qint64 readLineData (char *data, qint64 maxlen) override
 
virtual qint64 writeData (const char *data, qint64 len) override
 
- Protected Member Functions inherited from QIODevice
void setErrorString (const QString &str)
 
void setOpenMode (QIODevice::OpenMode openMode)
 
- Protected Member Functions inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
bool isSignalConnected (const QMetaMethod &signal) const const
 
int receivers (const char *signal) const const
 
QObjectsender () const const
 
int senderSignalIndex () const const
 
virtual void timerEvent (QTimerEvent *event)
 

Detailed Description

Class to allow for atomic file I/O, as well as utility functions.

The KSaveFile class has been made to write out changes to an existing file atomically. This means that either ALL changes will be written to the file, or NO changes have been written, and the original file (if any) has been unchanged. This is useful if you have lots of time-consuming processing to perform during which an interruption could occur, or if any error in the file structure will cause the entire file to be corrupt.

When you create a KSaveFile for a given file, a temporary file is instead created and all your I/O occurs in the save file. Once you call finalize() the temporary file is renamed to the target file, so that all your changes happen at once. If abort() is called then the temporary file is removed and the target file is untouched. KSaveFile derives from QFile so you can use it just as you would a normal QFile.

This class also includes several static utility functions available that can help ensure data integrity. See the individual functions for details.

Here is a quick example of how to use KSaveFile:

First we create the KSaveFile and open it.

KSaveFile saveFile;
saveFile.setFileName("/lib/foo/bar.dat");
if ( !saveFile.open() ) {
//Handle error
}

At this point the file "/lib/foo/bar.dat" has not been altered in any way. Now, let's write out some data to the file.

QTextStream stream ( &saveFile );
stream << "Add some data.";
// Perform long processing
stream << "Add some more data.";
stream.flush();

Even after writing this data, the target file "/lib/foo/bar.dat" still has not been altered in any way. Now that we are done writing our data, we can write out all the changes that we have made by calling finalize().

if ( !saveFile.finalize() ) {
//Handle error
}

If a user interruption or error occurred while we were writing out our changes, we would instead call abort() to cancel all the I/O without affecting the target file.

See also
QFile
Author
Jaison Lee lee.j[email protected]aiso[email protected][email protected][email protected]il.c[email protected]om
Waldo Bastian basti[email protected][email protected][email protected]de.or[email protected]g
Deprecated:
since 5.0, port to QSaveFile.

Definition at line 98 of file ksavefile.h.

Constructor & Destructor Documentation

KSaveFile::KSaveFile ( )

Default constructor.

Definition at line 72 of file ksavefile.cpp.

KSaveFile::KSaveFile ( const QString filename)
explicit

Creates a new KSaveFile and sets the target file to filename.

Parameters
filenamethe path of the file

Definition at line 77 of file ksavefile.cpp.

KSaveFile::~KSaveFile ( )
virtual

Destructor.

Note
If the file has been opened but not yet finalized, the destructor will call finalize(). If you do not want the target file to be affected you need to call abort() before destroying the object.

Definition at line 83 of file ksavefile.cpp.

Member Function Documentation

void KSaveFile::abort ( )

Discard changes without affecting the target file.

This will discard all changes that have been made to this file. The target file will not be altered in any way.

Definition at line 213 of file ksavefile.cpp.

bool KSaveFile::directWriteFallback ( ) const

Returns true if the fallback solution for saving files in read-only directories is enabled.

Since
4.10.3

Definition at line 298 of file ksavefile.cpp.

QFile::FileError KSaveFile::error ( ) const

Returns the last error that occurred.

Use this function to check for errors.

Returns
The last error that occurred, or QFile::NoError.

Definition at line 190 of file ksavefile.cpp.

QString KSaveFile::errorString ( ) const

Returns a human-readable description of the last error.

Use this function to get a human-readable description of the last error that occurred.

Returns
A string describing the last error that occurred.

Definition at line 199 of file ksavefile.cpp.

QString KSaveFile::fileName ( ) const
overridevirtual

Returns the name of the target file.

This function returns the name of the target file, or an empty QString if it has not yet been set.

Returns
The name of the target file.

Reimplemented from QFile.

Definition at line 208 of file ksavefile.cpp.

bool KSaveFile::finalize ( )

Finalize changes to the file.

This will commit all the changes that have been made to the file.

Returns
true if successful, or false if an error has occurred.

Definition at line 228 of file ksavefile.cpp.

bool KSaveFile::open ( OpenMode  flags = QIODevice::ReadWrite)
override

Open the save file.

This function will open the save file by creating a temporary file to write to. It will also check to ensure that there are sufficient permissions to write to the target file.

Parameters
flagsSets the QIODevice::OpenMode. It should contain the write flag, otherwise you have a save file you cannot save to.
Returns
true if successful, or false if an error has occurred.

Definition at line 90 of file ksavefile.cpp.

void KSaveFile::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.

Since
4.10.3

Definition at line 293 of file ksavefile.cpp.

void KSaveFile::setFileName ( const QString filename)

Set the target filename for the save file.

You must use this to set the filename of the target file if you do not use the contructor that does so.

Parameters
filenameName of the target file.

Definition at line 174 of file ksavefile.cpp.


The documentation for this class was generated from the following files:
This file is part of the KDE documentation.
Documentation copyright © 1996-2020 The KDE developers.
Generated on Wed Sep 23 2020 22:59:21 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.