CopperSpice API  1.9.2
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
 
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 (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
 
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
 
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 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, 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  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

The method exists() is used to verify if the file is present. To remove a file use the method remove().

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, you can also call the QIODevice methods read(), readLine(), readAll(), and write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.

The size of the file is returned by size(). You can 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:

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

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.

Using Streams to Read and Write to a File

QTextStream is responsible for converting the 8 bit data stored on disk into a UTF-8 QString. The encoding can be changed using setCodec(). This example uses QTextStream to read a text file line by line.

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);
}

To write text to a file use operator<<() and 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 QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means QFile is not suitable for reading and writing certain types of files such as device files on Unix platforms.

Platform Specific Issues

File permissions are handled differently on Linux, Mac OS X, and Windows. In a non writable directory on Linux, files can not be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.

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 file object.

QFile::QFile ( const QString name)

Constructs a new file object to represent the file with the given name.

QFile::QFile ( QObject parent)
explicit

Constructs a new file object with the given parent.

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

Constructs a new file object with the given parent to represent the file with the specified name.

QFile::~QFile ( )

Destroys the file object, closing it if necessary.

Method Documentation

bool QFile::copy ( const QString newName)

Copies the file currently specified by fileName() to a file called newName. Returns true if successful, otherwise returns false. If a file with the name newName already exists, copy() 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 name newName already exists, copy() returns false and QFile will not overwrite it.

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

Returns the Unicode version of the given localFileName. Refer to encodeName() for details.

QString QFile::decodeName ( const QByteArray localFileName)
static

This does the reverse of QFile::encodeName() using localFileName.

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

By default, this method converts fileName to the local 8-bit encoding determined by the user's locale. This is sufficient for file names that the user chooses. File names hard-coded into the application should only use 7-bit ASCII filename characters.

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

Returns true if the file specified by fileName() 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 name set by setFileName() or to the QFile constructors.

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

Reimplemented from QFileDevice::fileName()

Reimplemented in QTemporaryFile::fileName()

bool QFile::link ( const QString newName)

Creates a link named newName that points to the file currently specified by fileName(). What a link is depends on the underlying file system. Returns true if successful, otherwise returns false.

This method will not overwrite an already existing entity in the file system, in this case, link() will return false and set error() to return RenameError. To create a valid link on Windows 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 that points to the file oldName. What a link is depends on the underlying file system (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful, otherwise returns false.

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

Opens the existing file handle fHandle in the given mode using the given handleFlags. Returns true if successful, otherwise returns false.

When a QFile 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 calling close() closes the adopted handle. Otherwise, close() does not actually close the file but only flushes it.

#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();
}

If the file handle does not refer to a regular file on disk you may not be able to seek 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.

On Windows

The file handle must be opened in binary mode (the mode string 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.

You need to enable support for console applications in order to use the stdin, stdout, and stderr streams at the console.

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

Opens the existing file descriptor fd in the given mode. Returns true if successful, otherwise returns false.

When a QFile is opened using this method, behavior of close() is controlled by the handleFlags argument. If AutoCloseHandle is specified, and this method succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.

The QFile that is opened using this method is automatically set to be in raw mode, this means that the file input/output functions are slow. If you run into performance issues, you should try to use one of the other open functions.

Warning
If fd is not a regular file, e.g, it is 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). In those cases, size() returns 0. Refer to QIODevice::isSequential() for more information.
Since this method opens the file without specifying the file name it can not be used with a QFileInfo.
See also
close()
bool QFile::open ( OpenMode  mode)
overridevirtual

Opens the file using OpenMode mode, returning true if successful, otherwise false.

The mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered. In WriteOnly or ReadWrite mode, if the relevant 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()

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()

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 fileName(). 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 fileName given. Returns true if successful, otherwise returns false.

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

Renames the file currently specified by fileName() to newName. Returns true if successful, otherwise returns false. If a file with the name newName already exists, rename() returns false and QFile will not overwrite it. 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 the name newName already exists, rename() returns false and it QFile will not overwrite it.

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

Sets filename to size (in bytes) sz. Returns true if the file if the resize succeeds, false otherwise. If sz is larger than filename currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.

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

Sets the file size (in bytes) sz. Returns true if the file if the resize succeeds, false otherwise. If sz is larger than the file currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.

See also
size(), setFileName()

Reimplemented from QFileDevice::resize()

void QFile::setDecodingFunction ( DecoderFn  function)
static

Sets the function for decoding 8-bit file names. The default uses the locale-specific 8-bit encoding.

Warning
This method is not conditionally thread safe.
See also
setEncodingFunction(), decodeName()
void QFile::setEncodingFunction ( EncoderFn  function)
static

Sets the function for encoding Unicode file names. The default encodes in the locale-specific 8-bit encoding.

Warning
This method is not conditionally thread safe.
See also
encodeName(), setDecodingFunction()
void QFile::setFileName ( const QString name)

Sets the name of the file. The name can have no path, a relative path, or an absolute path. Do not call this function if the file has already been opened. If the file name has no path or a relative path, the path used will be the application's current directory path at the time of the open() call.

QFile file;
file.setFileName("readme.txt");
file.open(QIODevice::ReadOnly); // opens "/home/readme.txt" under Unix

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

See also
fileName(), QFileInfo, QDir
bool QFile::setPermissions ( const QString fileName,
Permissions  permissions 
)
static

Sets the permissions for fileName file to permissions.

bool QFile::setPermissions ( Permissions  permissions)
overridevirtual

Sets the permissions for the file to the permissions specified. 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 the file will contain data when read() is called.

Reimplemented from QIODevice::size()

QString QFile::symLinkTarget ( ) const
inline

Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or an empty string if the object is not a symbolic link. This name may not represent an existing file since it is only a string. QFile::exists() returns true if the symlink points to an existing file.

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

Returns the absolute path of the given fileName or directory referred to by the symlink (or shortcut on Windows) specified by fileName, or returns an empty string if the fileName does not correspond to a symbolic link.

The fileName may not represent an actual file since it is only a string. QFile::exists() returns true if the symlink points to an existing file.