CopperSpice API  2.0.0
QFile Class Reference

The QFile class is used to read and write to an open file. More...

Inheritance diagram for QFile:
QFileDevice QIODevice QObject QTemporaryFile

Public Typedefs

using DecoderFn = QString (*)(const QByteArray &localfileName)
 
using EncoderFn = QByteArray (*)(const QString &fileName)
 
- Public Typedefs inherited from QFileDevice
using FileHandleFlags = QFlags< FileHandleFlag >
 
using Permissions = QFlags< Permission >
 
- Public Typedefs inherited from QIODevice
using OpenMode = QFlags< OpenModeFlag >
 

Public Methods

 QFile ()
 
 QFile (const QString &name)
 
 QFile (const QString &name, QObject *parent)
 
 QFile (QObject *parent)
 
 ~QFile ()
 
bool copy (const QString &newName)
 
bool exists () const
 
QString fileName () const override
 
bool link (const QString &newName)
 
bool open (FILE *fHandle, OpenMode mode, FileHandleFlags handleFlags=DontCloseHandle)
 
bool open (int fd, OpenMode mode, FileHandleFlags handleFlags=DontCloseHandle)
 
bool open (OpenMode mode) override
 
QFileDevice::Permissions permissions () const override
 
QString readLink () const
 
bool remove ()
 
bool rename (const QString &newName)
 
bool resize (qint64 sz) override
 
void setFileName (const QString &name)
 
bool setPermissions (QFileDevice::Permissions permissions) override
 
qint64 size () const override
 
QString symLinkTarget () const
 
- Public Methods inherited from QFileDevice
 ~QFileDevice ()
 
bool atEnd () const override
 
void close () override
 
FileError error () const
 
QDateTime fileTime (QFileDevice::FileTimeType type) const
 
bool flush ()
 
int handle () const
 
bool isSequential () const override
 
ucharmap (qint64 offset, qint64 size, MemoryMapFlags flags=NoOptions)
 
qint64 pos () const override
 
bool seek (qint64 pos) override
 
bool setFileTime (const QDateTime &newTime, QFileDevice::FileTimeType type)
 
qint64 size () const override
 
bool unmap (uchar *address)
 
void unsetError ()
 
- Public Methods inherited from QIODevice
 QIODevice ()
 
 QIODevice (QObject *parent)
 
virtual ~QIODevice ()
 
virtual qint64 bytesAvailable () const
 
virtual qint64 bytesToWrite () const
 
virtual bool canReadLine () const
 
QString errorString () const
 
bool getChar (char *c)
 
bool isOpen () const
 
bool isReadable () const
 
bool isTextModeEnabled () const
 
bool isWritable () const
 
OpenMode openMode () 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 ()
 
qint64 readLine (char *data, qint64 maxSize)
 
QByteArray readLine (qint64 maxSize=0)
 
virtual bool reset ()
 
void setTextModeEnabled (bool enabled)
 
void ungetChar (char c)
 
virtual bool waitForBytesWritten (int msecs)
 
virtual bool waitForReadyRead (int msecs)
 
qint64 write (const char *data)
 
qint64 write (const char *data, qint64 maxSize)
 
qint64 write (const QByteArray &data)
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &childName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Static Public Methods

static bool copy (const QString &oldName, const QString &newName)
 
static QString decodeName (const char *localFileName)
 
static QString decodeName (const QByteArray &localFileName)
 
static QByteArray encodeName (const QString &fileName)
 
static bool exists (const QString &fileName)
 
static bool link (const QString &oldName, const QString &newName)
 
static QFileDevice::Permissions permissions (const QString &fileName)
 
static QString readLink (const QString &fileName)
 
static bool remove (const QString &fileName)
 
static bool rename (const QString &oldName, const QString &newName)
 
static bool resize (const QString &filename, qint64 sz)
 
static void setDecodingFunction (DecoderFn function)
 
static void setEncodingFunction (EncoderFn function)
 
static bool setPermissions (const QString &fileName, QFileDevice::Permissions permissions)
 
static QString symLinkTarget (const QString &fileName)
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 

Friends

class QTemporaryFile
 

Additional Inherited Members

- Public Types inherited from QFileDevice
enum  FileError
 
enum  FileHandleFlag
 
enum  FileTimeType
 
enum  MemoryMapFlags
 
enum  Permission
 
- Public Types inherited from QIODevice
enum  OpenModeFlag
 
- Public Signals inherited from QIODevice
void aboutToClose ()
 
void bytesWritten (qint64 bytes)
 
void readChannelFinished ()
 
void readyRead ()
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 
- Public Slots inherited from QObject
void deleteLater ()
 
- Protected Methods inherited from QFileDevice
qint64 readData (char *data, qint64 maxSize) override
 
qint64 readLineData (char *data, qint64 maxSize) override
 
qint64 writeData (const char *data, qint64 maxSize) override
 
- Protected Methods inherited from QIODevice
void setErrorString (const QString &errorString)
 
void setOpenMode (OpenMode openMode)
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QFile class is used to read and write to an open file. QFile is an I/O device for reading and writing text and binary files and resources. A QFile can be used with a QTextStream or QDataStream.

The file name is usually passed in the constructor however it can be set at any time using setFileName(). QFile expects the file separator to be '/' regardless of the operating system. The use of other separators like '\' is not supported.

Methods

A file is opened, closed, or flushed by calling open(), close(), or flush() respectively. Calling exists() is used to verify if the file is present on disk. To delete a file call remove().

Data is normally read and written using QDataStream or QTextStream. Call the QIODevice methods read(), readLine(), readAll(), and write() for low-level file IO.

To obtain the current file position using pos() or move to a new file position using seek(). When you are at the end of the file atEnd() will returns true. More advanced file system related operations are provided by QFileInfo and QDir.

Reading Files Directly

The following example reads a text file line by line using low-level file IO.

The QIODevice::Text flag passed to open() is used to convert Windows style line terminators "\\r\\n" into C++ style terminators "\\n". By default QFile does not convert line endings.

QFile file("in.txt");
if (! file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
while (! file.atEnd()) {
QByteArray line = file.readLine();
process_line(line);
}

Using Streams to Read and Write to a File

This example uses QTextStream to read a text file line by line.

QTextStream is responsible for converting the 8 bit data stored on disk into a UTF-8 QString. The encoding can be changed using setCodec().

QFile file("in.txt");
if (! file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream in(&file);
while (! in.atEnd()) {
QString line = in.readLine();
process_line(line);
}

Use the following code to write text to a file use operator<<() as shown below.

QFile file("out.txt");
if (! file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return;
}
QTextStream out(&file);
out << "The magic number is " << 42 << "\n";

Unix Special Files

On Unix systems there are special files in /proc and /sys where calling size() will always return 0. However, reading from the file will return data. When reading from one of these files do not use atEnd() to determine if there is more data to read. Instead either call readAll(), read(), or readLine() repeatedly until no more data can be read.

The next example uses QTextStream to read /proc/modules line by line.

QFile file("/proc/modules");
if (! file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream in(&file);
QString line = in.readLine();
while (! line.isNull()) {
process_line(line);
line = in.readLine();
}

Signals

Unlike other classes which inherit from QIODevice, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. For this reason QFile should not be used for reading and writing certain types of special files like named pipes on Unix platforms.

See also
QTextStream, QDataStream, QFileInfo, QDir, Resource System

Member Typedef Documentation

This is a typedef for a pointer to a function with the following signature.

QString myDecoderFunc(const QByteArray &localFileName);
See also
setDecodingFunction()

This is a typedef for a pointer to a function with the following signature.

QByteArray myEncoderFunc(const QString &fileName);
See also
setEncodingFunction(), encodeName()

Constructor & Destructor Documentation

QFile::QFile ( )

Constructs a new QFile.

QFile::QFile ( const QString name)

Constructs a new QFile with the given name.

QFile::QFile ( QObject parent)
explicit

Constructs a new QFile with the given parent.

QFile::QFile ( const QString name,
QObject parent 
)

Constructs a new QFile with the given name and parent.

QFile::~QFile ( )

Destroys the QFile, closing the file if necessary.

Method Documentation

bool QFile::copy ( const QString newName)

Copies the current file to a new file using the given newName. Returns true if successful, otherwise returns false. If a file with the given name already exists this method returns false and QFile will not overwrite it. The source file is closed before it is copied.

See also
setFileName()
bool QFile::copy ( const QString oldName,
const QString newName 
)
static

Copies the file oldName to newName. Returns true if successful, otherwise returns false. If a file with the given name already exists, this method returns false and QFile will not overwrite it.

See also
rename()
QString QFile::decodeName ( const char *  localFileName)
inlinestatic

This method converts the given localFileName from the platform native encoding to UTF-8.

QString QFile::decodeName ( const QByteArray localFileName)
static

This method converts the given localFileName from the platform native encoding to UTF-8.

See also
encodeName(), setDecodingFunction()
QByteArray QFile::encodeName ( const QString fileName)
static

This method converts fileName from UTF-8 to the platform native encoding.

See also
decodeName(), setEncodingFunction()
bool QFile::exists ( ) const

Returns true if the file specified by QFile exists, otherwise returns false.

See also
fileName(), setFileName()
bool QFile::exists ( const QString fileName)
static

Returns true if the file specified by fileName exists, otherwise returns false.

QString QFile::fileName ( ) const
overridevirtual

Returns the file name specified by QFile.

See also
setFileName(), QFileInfo::fileName()

Reimplemented from QFileDevice::fileName()

Reimplemented in QTemporaryFile::fileName()

bool QFile::link ( const QString newName)

Creates a link named newName which points to the file specified by QFile. Returns true if successful. This method will not overwrite an existing file. If newName already exists this method will set error() to RenameError and return false.

The definition of a link depends on the underlying file system. On Unix it is a symbolic link. On Windows a link is a shortcut. To create a valid link on Windows the given newName must have a ".lnk" file extension.

See also
setFileName()
bool QFile::link ( const QString oldName,
const QString newName 
)
static

Creates a link named newName which points to the file oldName. Returns true if successful. This method will not overwrite an existing file. If newName already exists this method will set error() to RenameError and return false.

The definition of a link depends on the underlying file system. On Unix it is a symbolic link. On Windows a link is a shortcut. To create a valid link on Windows the given newName must have a ".lnk" file extension.

See also
link()
bool QFile::open ( FILE *  fHandle,
OpenMode  mode,
FileHandleFlags  handleFlags = DontCloseHandle 
)

Attaches the current QFile to an existing C file handle specified by fHandle using mode and handleFlags. Returns true if successful, otherwise returns false.

When a file is opened using this method the behavior of close() is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified and the open method succeeds, then QFile takes ownership of the file handle. When the QFile is closed, the file handle will be passed to fclose(). Otherwise, QFile::close() will flush the file but not close the file handle.

If the file handle does not refer to a regular file on disk seeking may not work and the size() method will return 0. Refer to QIODevice::isSequential() for more information. Since this method opens the file without specifying the file name you can not pass this QFile to create a QFileInfo object.

#include <stdio.h>
void printError(const char* msg)
{
QFile file;
file.open(stderr, QIODevice::WriteOnly);
file.write(msg, qstrlen(msg)); // write to stderr
file.close();
}

Windows

The file handle must be opened in binary mode (the mode must contain 'b', as in "rb" or "wb") when accessing files and other random-access devices. CopperSpice will translate the end-of-line characters if you pass QIODevice::Text to mode. Sequential devices such as stdin and stdout are unaffected by this limitation.

bool QFile::open ( int  fd,
OpenMode  mode,
FileHandleFlags  handleFlags = DontCloseHandle 
)

Attaches the current QFile to an existing POSIX file descriptor specified by fd using mode and handleFlags. Returns true if successful, otherwise returns false.

When a file is opened using this method the behavior of close() is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified and the open method succeeds, then QFile takes ownership of the file descriptor. When the QFile is closed, the file descriptor will be passed to POSIX close() function. Otherwise, QFile::close() will flush the file but not close the file descriptor.

This method sets the current QFile to raw mode. The file input/output methods will be slower. If the application has performance issues consider using one of the other open methods.

If the file descriptor does not refer to a regular file on disk seeking may not work and the size() method will return 0. Refer to QIODevice::isSequential() for more information. Since this method opens the file without specifying the file name you can not pass this QFile to create a QFileInfo object.

See also
close()
bool QFile::open ( OpenMode  mode)
overridevirtual

Opens the file using the given mode and returns true if successful, otherwise false. The mode can be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite.

The mode may also contain additional flags such as QIODevice::Text and QIODevice::Unbuffered.

In the WriteOnly or ReadWrite mode, if the file does not already exist this method will try to create a new file before opening it.

See also
QIODevice::OpenMode, setFileName()

Reimplemented from QIODevice::open()

Reimplemented in QTemporaryFile::open()

QFileDevice::Permissions QFile::permissions ( ) const
overridevirtual

Returns the complete OR-ed together combination of QFile::Permission for the file.

See also
setPermissions(), setFileName()

Reimplemented from QFileDevice::permissions()

QFileDevice::Permissions QFile::permissions ( const QString fileName)
static

Returns the complete OR-ed together combination of QFile::Permission for fileName.

QString QFile::readLink ( ) const
deprecated
QString QFile::readLink ( const QString fileName)
deprecatedstatic
bool QFile::remove ( )

Removes the file specified by the current QFile. Returns true if successful, otherwise returns false. The file is closed before it is removed.

See also
setFileName()
bool QFile::remove ( const QString fileName)
static

Removes the file specified by the given fileName. Returns true if successful, otherwise returns false.

See also
remove()
bool QFile::rename ( const QString newName)

Renames the file specified by the current QFile to newName. Returns true if successful, otherwise returns false. If a file with newName already exists, this method will return false and the file will not be renamed. The file is closed before it is renamed.

See also
setFileName()
bool QFile::rename ( const QString oldName,
const QString newName 
)
static

Renames the file oldName to newName. Returns true if successful, otherwise returns false. If a file with newName already exists, this method will return false and the file will not be renamed.

See also
rename()
bool QFile::resize ( const QString filename,
qint64  sz 
)
static

Sets the file with the given filename to size (in bytes) sz. Returns true if the resize is successful, otherwise returns false. If sz is larger than the current size of the file, then new bytes will be set to 0. If sz is smaller the file is truncated.

See also
resize()
bool QFile::resize ( qint64  sz)
overridevirtual

Sets the file size (in bytes) to sz. Returns true if the resize is successful, otherwise returns false. If sz is larger than the current size of the file, then new bytes will be set to 0. If sz is smaller the file is truncated.

See also
setFileName(), size()

Reimplemented from QFileDevice::resize()

void QFile::setDecodingFunction ( DecoderFn  function)
static

Uses function to convert file names from the platform encoding to UTF-8.

See also
setEncodingFunction(), decodeName()
void QFile::setEncodingFunction ( EncoderFn  function)
static

Uses function to convert file names from UTF-8 to the platform encoding.

See also
encodeName(), setDecodingFunction()
void QFile::setFileName ( const QString name)

Sets the name of the file. The name may have no path, a relative path, or an absolute path. This method must be called before the file is opened. The path for the file name is relative to the application's current directory when open is called().

The directory separator "/" works for all operating systems supported by CopperSpice.

QFile file;
file.setFileName("readme.txt");
file.open(QIODevice::ReadOnly); // opens "/home/readme.txt"
See also
fileName(), QDir, QFileInfo
bool QFile::setPermissions ( const QString fileName,
QFileDevice::Permissions  permissions 
)
static

Sets the permissions for fileName to permissions.

bool QFile::setPermissions ( QFileDevice::Permissions  permissions)
overridevirtual

Sets the permissions for the file to permissions. Returns true if successful, or false if the permissions can not be modified.

See also
permissions(), setFileName()

Reimplemented from QFileDevice::setPermissions()

qint64 QFile::size ( ) const
overridevirtual

Returns the size of the file. On Unix special files like those in /proc, will have a size of 0 even though may the file may contain data when read() is called.

Reimplemented from QIODevice::size()

QString QFile::symLinkTarget ( ) const
inline

Returns the absolute path for the target of the Unix symlink or Windows shortcut corresponding to the file specified by the current QFile. An empty string will be returned if the filename does not correspond to a symbolic link or shortcut.

See also
fileName(), setFileName()
QString QFile::symLinkTarget ( const QString fileName)
inlinestatic

Returns the absolute path for the target of the Unix symlink or Windows shortcut with the given fileName. An empty string will be returned if the filename does not correspond to a symbolic link or shortcut.