Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
QTemporaryFile Class Reference

\inmodule QtCore \reentrant More...

#include <qtemporaryfile.h>

+ Inheritance diagram for QTemporaryFile:
+ Collaboration diagram for QTemporaryFile:

Public Member Functions

 QTemporaryFile ()
 Constructs a QTemporaryFile using as file template the application name returned by QCoreApplication::applicationName() (otherwise qt_temp) followed by ".XXXXXX".
 
 QTemporaryFile (const QString &templateName)
 Constructs a QTemporaryFile with a template filename of templateName.
 
 QTemporaryFile (QObject *parent)
 Constructs a QTemporaryFile (with the given parent) using as file template the application name returned by QCoreApplication::applicationName() (otherwise qt_temp) followed by ".XXXXXX".
 
 QTemporaryFile (const QString &templateName, QObject *parent)
 Constructs a QTemporaryFile with a template filename of templateName and the specified parent.
 
 ~QTemporaryFile ()
 Destroys the temporary file object, the file is automatically closed if necessary and if in auto remove mode it will automatically delete the file.
 
bool autoRemove () const
 Returns true if the QTemporaryFile is in auto remove mode.
 
void setAutoRemove (bool b)
 Sets the QTemporaryFile into auto-remove mode if b is true.
 
bool open ()
 A QTemporaryFile will always be opened in QIODevice::ReadWrite mode, this allows easy access to the data in the file.
 
QString fileName () const override
 Returns the complete unique filename backing the QTemporaryFile object.
 
QString fileTemplate () const
 Returns the set file template.
 
void setFileTemplate (const QString &name)
 Sets the static portion of the file name to name.
 
bool rename (const QString &newName)
 Renames the current temporary file to newName and returns true if it succeeded.
 
- Public Member Functions inherited from QFile
 QFile ()
 Constructs a QFile object.
 
QFILE_MAYBE_EXPLICIT QFile (const QString &name)
 
 QFile (QObject *parent)
 Constructs a new file object with the given parent.
 
 QFile (const QString &name, QObject *parent)
 Constructs a new file object with the given parent to represent the file with the specified name.
 
 ~QFile ()
 Destroys the file object, closing it if necessary.
 
QString fileName () const override
 Returns the name set by setFileName() or to the QFile constructors.
 
void setFileName (const QString &name)
 Sets the name of the file.
 
bool exists () const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns true if the file specified by fileName() exists; otherwise returns false.
 
QString symLinkTarget () const
 
bool remove ()
 Removes the file specified by fileName().
 
bool moveToTrash ()
 
bool rename (const QString &newName)
 Renames the file currently specified by fileName() to newName.
 
bool link (const QString &newName)
 Creates a link named linkName that points to the file currently specified by fileName().
 
bool copy (const QString &newName)
 Copies the file named fileName() to newName.
 
bool open (OpenMode flags) override
 Opens the file using OpenMode mode, returning true if successful; otherwise false.
 
bool open (OpenMode flags, Permissions permissions)
 
bool open (FILE *f, OpenMode ioFlags, FileHandleFlags handleFlags=DontCloseHandle)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Opens the existing file handle fh in the given mode.
 
bool open (int fd, OpenMode ioFlags, FileHandleFlags handleFlags=DontCloseHandle)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Opens the existing file descriptor fd in the given mode.
 
qint64 size () const override
 \reimp
 
bool resize (qint64 sz) override
 \reimp
 
Permissions permissions () const override
 \reimp
 
bool setPermissions (Permissions permissionSpec) override
 Sets the permissions for the file to the permissions specified.
 
- Public Member Functions inherited from QFileDevice
 ~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.
 
ucharmap (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)
 
- Public Member Functions inherited from QIODevice
 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.
 
- Public Member Functions inherited from QObject
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< QStringbindableObjectName ()
 
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).
 
QThreadthread () 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 >
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 QObjectListchildren () 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< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () 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.
 

Static Public Member Functions

static QTemporaryFilecreateNativeFile (const QString &fileName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Works on the given fileName rather than an existing QFile object.
 
static QTemporaryFilecreateNativeFile (QFile &file)
 If file is not already a native file, then a QTemporaryFile is created in QDir::tempPath(), the contents of file is copied into it, and a pointer to the temporary file is returned.
 
- Static Public Member Functions inherited from QFile
static QByteArray encodeName (const QString &fileName)
 Converts fileName to an 8-bit encoding that you can use in native APIs.
 
static QString decodeName (const QByteArray &localFileName)
 This does the reverse of QFile::encodeName() using localFileName.
 
static QString decodeName (const char *localFileName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the Unicode version of the given localFileName.
 
static bool exists (const QString &fileName)
 Returns true if the file specified by fileName exists; otherwise returns false.
 
static QString symLinkTarget (const QString &fileName)
 
static bool remove (const QString &fileName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Removes the file specified by the fileName given.
 
static bool moveToTrash (const QString &fileName, QString *pathInTrash=nullptr)
 
static bool rename (const QString &oldName, const QString &newName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Renames the file oldName to newName.
 
static bool link (const QString &fileName, const QString &newName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Creates a link named linkName that points to the file fileName.
 
static bool copy (const QString &fileName, const QString &newName)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Copies the file named fileName to newName.
 
static bool resize (const QString &filename, qint64 sz)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Sets fileName to size (in bytes) sz.
 
static Permissions permissions (const QString &filename)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the complete OR-ed together combination of QFile::Permission for fileName.
 
static bool setPermissions (const QString &filename, Permissions permissionSpec)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Sets the permissions for fileName file to permissions.
 
- Static Public Member Functions inherited from QObject
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)
 

Protected Member Functions

bool open (OpenMode flags) override
 \reimp
 
- Protected Member Functions inherited from QFile
 QFile (QFilePrivate &dd, QObject *parent=nullptr)
 
- Protected Member Functions inherited from QFileDevice
 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
 
- Protected Member Functions inherited from QIODevice
 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.
 
- Protected Member Functions inherited from QObject
QObjectsender () 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)
 
- Protected Member Functions inherited from QIODeviceBase
 ~QIODeviceBase ()=default
 

Friends

class QFile
 
class QLockFilePrivate
 

Additional Inherited Members

- Public Types inherited from QFileDevice
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 }
 
- Public Types inherited from QIODeviceBase
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...
 
- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- Signals inherited from QIODevice
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 ()
 
- Signals inherited from QObject
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.
 
- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Detailed Description

\inmodule QtCore \reentrant

The QTemporaryFile class is an I/O device that operates on temporary files.

QTemporaryFile is used to create unique temporary files safely. The file itself is created by calling open(). The name of the temporary file is guaranteed to be unique (i.e., you are guaranteed to not overwrite an existing file), and the file will subsequently be removed upon destruction of the QTemporaryFile object. This is an important technique that avoids data corruption for applications that store data in temporary files. The file name is either auto-generated, or created based on a template, which is passed to QTemporaryFile's constructor.

Example:

// Within a function/method...
if (file.open()) {
// file.fileName() returns the unique file name
}
// The QTemporaryFile destructor removes the temporary file
// as it goes out of scope.
bool open(OpenMode flags) override
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition qfile.cpp:881
\inmodule QtCore \reentrant
QFile file
[0]

Reopening a QTemporaryFile after calling close() is safe. For as long as the QTemporaryFile object itself is not destroyed, the unique temporary file will exist and be kept open internally by QTemporaryFile.

The file name of the temporary file can be found by calling fileName(). Note that this is only defined after the file is first opened; the function returns an empty string before this.

A temporary file will have some static part of the name and some part that is calculated to be unique. The default filename will be determined from QCoreApplication::applicationName() (otherwise qt_temp) and will be placed into the temporary path as returned by QDir::tempPath(). If you specify your own filename, a relative file path will not be placed in the temporary directory by default, but be relative to the current working directory. It is important to specify the correct directory if the rename() function will be called, as QTemporaryFile can only rename files within the same volume / filesystem as the temporary file itself was created on.

Specified filenames can contain the following template XXXXXX (six upper case "X" characters), which will be replaced by the auto-generated portion of the filename. Note that the template is case sensitive. If the template is not present in the filename, QTemporaryFile appends the generated part to the filename given.

Note
On Linux, QTemporaryFile will attempt to create unnamed temporary files. If that succeeds, open() will return true but exists() will be false. If you call fileName() or any function that calls it, QTemporaryFile will give the file a name, so most applications will not see a difference.
See also
QDir::tempPath(), QFile

Definition at line 22 of file qtemporaryfile.h.

Constructor & Destructor Documentation

◆ QTemporaryFile() [1/4]

QTemporaryFile::QTemporaryFile ( )

Constructs a QTemporaryFile using as file template the application name returned by QCoreApplication::applicationName() (otherwise qt_temp) followed by ".XXXXXX".

The file is stored in the system's temporary directory, QDir::tempPath().

See also
setFileTemplate(), QDir::tempPath()

Definition at line 628 of file qtemporaryfile.cpp.

Referenced by createNativeFile().

+ Here is the caller graph for this function:

◆ QTemporaryFile() [2/4]

QTemporaryFile::QTemporaryFile ( const QString templateName)
explicit

Constructs a QTemporaryFile with a template filename of templateName.

Upon opening the temporary file this will be used to create a unique filename.

If the templateName does not contain XXXXXX it will automatically be appended and used as the dynamic portion of the filename.

If templateName is a relative path, the path will be relative to the current working directory. You can use QDir::tempPath() to construct templateName if you want use the system's temporary directory. It is important to specify the correct directory if the rename() function will be called, as QTemporaryFile can only rename files within the same volume / filesystem as the temporary file itself was created on.

See also
open(), fileTemplate()

Definition at line 651 of file qtemporaryfile.cpp.

◆ QTemporaryFile() [3/4]

QTemporaryFile::QTemporaryFile ( QObject parent)
explicit

Constructs a QTemporaryFile (with the given parent) using as file template the application name returned by QCoreApplication::applicationName() (otherwise qt_temp) followed by ".XXXXXX".

The file is stored in the system's temporary directory, QDir::tempPath().

See also
setFileTemplate()

Definition at line 664 of file qtemporaryfile.cpp.

◆ QTemporaryFile() [4/4]

QTemporaryFile::QTemporaryFile ( const QString templateName,
QObject parent 
)

Constructs a QTemporaryFile with a template filename of templateName and the specified parent.

Upon opening the temporary file this will be used to create a unique filename.

If the templateName does not contain XXXXXX it will automatically be appended and used as the dynamic portion of the filename.

If templateName is a relative path, the path will be relative to the current working directory. You can use QDir::tempPath() to construct templateName if you want use the system's temporary directory. It is important to specify the correct directory if the rename() function will be called, as QTemporaryFile can only rename files within the same volume / filesystem as the temporary file itself was created on.

See also
open(), fileTemplate()

Definition at line 687 of file qtemporaryfile.cpp.

◆ ~QTemporaryFile()

QTemporaryFile::~QTemporaryFile ( )

Destroys the temporary file object, the file is automatically closed if necessary and if in auto remove mode it will automatically delete the file.

See also
autoRemove()

Definition at line 700 of file qtemporaryfile.cpp.

References QFileDevice::close(), d, and QFile::remove().

+ Here is the call graph for this function:

Member Function Documentation

◆ autoRemove()

bool QTemporaryFile::autoRemove ( ) const

Returns true if the QTemporaryFile is in auto remove mode.

Auto-remove mode will automatically delete the filename from disk upon destruction. This makes it very easy to create your QTemporaryFile object on the stack, fill it with data, read from it, and finally on function return it will automatically clean up after itself.

Auto-remove is on by default.

See also
setAutoRemove(), remove()

Definition at line 731 of file qtemporaryfile.cpp.

References d.

◆ createNativeFile() [1/2]

QTemporaryFile * QTemporaryFile::createNativeFile ( const QString fileName)
inlinestatic

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Works on the given fileName rather than an existing QFile object.

Definition at line 51 of file qtemporaryfile.h.

References file, and fileName.

Referenced by QMediaPlayerPrivate::setMedia().

+ Here is the caller graph for this function:

◆ createNativeFile() [2/2]

QTemporaryFile * QTemporaryFile::createNativeFile ( QFile file)
static

If file is not already a native file, then a QTemporaryFile is created in QDir::tempPath(), the contents of file is copied into it, and a pointer to the temporary file is returned.

Does nothing and returns 0 if file is already a native file.

For example:

QFile f(":/resources/file.txt");
QTemporaryFile::createNativeFile(f); // Returns a pointer to a temporary file
QFile f("/users/qt/file.txt");
\inmodule QtCore
Definition qfile.h:93
static QTemporaryFile * createNativeFile(const QString &fileName)
This is an overloaded member function, provided for convenience. It differs from the above function o...
GLfloat GLfloat f
See also
QFileInfo::isNativePath()

Definition at line 878 of file qtemporaryfile.cpp.

References QTemporaryFile(), QFileDevice::close(), engine, file, QAbstractFileEngine::FlagsMask, QIODevice::isOpen(), QAbstractFileEngine::LocalDiskFlag, QFile::open(), QFileDevice::pos(), QIODevice::read(), QIODeviceBase::ReadOnly, ret, and QFileDevice::seek().

+ Here is the call graph for this function:

◆ fileName()

QString QTemporaryFile::fileName ( ) const
overridevirtual

Returns the complete unique filename backing the QTemporaryFile object.

This string is null before the QTemporaryFile is opened, afterwards it will contain the fileTemplate() plus additional characters to make it unique.

See also
fileTemplate()

Reimplemented from QFile.

Definition at line 770 of file qtemporaryfile.cpp.

References d, QAbstractFileEngine::DefaultName, and QTemporaryFilePrivate::materializeUnnamedFile().

Referenced by createTemporaryItemCopy(), QRhiMetal::pipelineCacheData(), QRhiMetal::setPipelineCacheData(), QDBusTrayIcon::showMessage(), and QDBusTrayIcon::updateIcon().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fileTemplate()

QString QTemporaryFile::fileTemplate ( ) const

Returns the set file template.

The default file template will be called qcoreappname.XXXXXX and be placed in QDir::tempPath().

See also
setFileTemplate()

Definition at line 788 of file qtemporaryfile.cpp.

References d.

◆ open() [1/2]

bool QTemporaryFile::open ( )
inline

A QTemporaryFile will always be opened in QIODevice::ReadWrite mode, this allows easy access to the data in the file.

This function will return true upon success and will set the fileName() to the unique filename used.

See also
fileName()

Definition at line 42 of file qtemporaryfile.h.

References open(), and QIODeviceBase::ReadWrite.

Referenced by createTemporaryItemCopy(), open(), QRhiMetal::pipelineCacheData(), and QRhiMetal::setPipelineCacheData().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ open() [2/2]

bool QTemporaryFile::open ( OpenMode  flags)
overrideprotected

\reimp

Creates a unique file name for the temporary file, and opens it. You can get the unique name later by calling fileName(). The file is guaranteed to have been created by this function (i.e., it has never existed before).

Definition at line 924 of file qtemporaryfile.cpp.

References d, QAbstractFileEngine::DefaultName, QFile::open(), and QIODevice::setOpenMode().

+ Here is the call graph for this function:

◆ rename()

bool QTemporaryFile::rename ( const QString newName)

Renames the current temporary file to newName and returns true if it succeeded.

This function has an important difference compared to QFile::rename(): it will not perform a copy+delete if the low-level system call to rename the file fails, something that could happen if newName specifies a file in a different volume or filesystem than the temporary file was created on. In other words, QTemporaryFile only supports atomic file renaming.

This functionality is intended to support materializing the destination file with all contents already present, so another process cannot see an incomplete file in the process of being written. The \l QSaveFile class can be used for a similar purpose too, particularly if the destination file is not temporary.

See also
QSaveFile, QSaveFile::commit(), QFile::rename()

Definition at line 833 of file qtemporaryfile.cpp.

References QFileDevice::close(), d, QFileDevice::error(), QFileDevice::NoError, QFile::rename(), QFileDevice::RenameError, and QFileDevice::unsetError().

+ Here is the call graph for this function:

◆ setAutoRemove()

void QTemporaryFile::setAutoRemove ( bool  b)

Sets the QTemporaryFile into auto-remove mode if b is true.

Auto-remove is on by default.

If you set this property to false, ensure the application provides a way to remove the file once it is no longer needed, including passing the responsibility on to another process. Always use the fileName() function to obtain the name and never try to guess the name that QTemporaryFile has generated.

On some systems, if fileName() is not called before closing the file, the temporary file may be removed regardless of the state of this property. This behavior should not be relied upon, so application code should either call fileName() or leave the auto removal functionality enabled.

See also
autoRemove(), remove()

Definition at line 755 of file qtemporaryfile.cpp.

References d.

Referenced by createTemporaryItemCopy().

+ Here is the caller graph for this function:

◆ setFileTemplate()

void QTemporaryFile::setFileTemplate ( const QString name)

Sets the static portion of the file name to name.

If the file template contains XXXXXX that will automatically be replaced with the unique part of the filename, otherwise a filename will be determined automatically based on the static portion specified.

If name contains a relative file path, the path will be relative to the current working directory. You can use QDir::tempPath() to construct name if you want use the system's temporary directory. It is important to specify the correct directory if the rename() function will be called, as QTemporaryFile can only rename files within the same volume / filesystem as the temporary file itself was created on.

See also
fileTemplate()

Definition at line 809 of file qtemporaryfile.cpp.

References d.

Friends And Related Symbol Documentation

◆ QFile

friend class QFile
friend

Definition at line 59 of file qtemporaryfile.h.

◆ QLockFilePrivate

friend class QLockFilePrivate
friend

Definition at line 60 of file qtemporaryfile.h.


The documentation for this class was generated from the following files: