Qt 4.8
Public Types | Public Functions | Static Public Functions | Protected Functions | List of all members
QFile Class Reference

The QFile class provides an interface for reading from and writing to files. More...

#include <qfile.h>

Inheritance diagram for QFile:
QIODevice QObject QTemporaryFile

Public Types

typedef QString(* DecoderFn) (const QByteArray &localfileName)
 This is a typedef for a pointer to a function with the following signature: More...
 
typedef QByteArray(* EncoderFn) (const QString &fileName)
 This is a typedef for a pointer to a function with the following signature: More...
 
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  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  MemoryMapFlags { NoOptions = 0 }
 This enum describes special options that may be used by the map() function. More...
 
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...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Public Functions

bool atEnd () const
 Returns true if the end of the file has been reached; otherwise returns false. More...
 
virtual void close ()
 Calls QFile::flush() and closes the file. More...
 
bool copy (const QString &newName)
 Copies the file currently specified by fileName() to a file called newName. More...
 
FileError error () const
 Returns the file error status. More...
 
bool exists () const
 Returns true if the file specified by fileName() exists; otherwise returns false. More...
 
virtual QAbstractFileEnginefileEngine () const
 Returns the QIOEngine for this QFile object. More...
 
QString fileName () const
 Returns the name set by setFileName() or to the QFile constructors. More...
 
bool flush ()
 Flushes any buffered data to the file. More...
 
int handle () const
 Returns the file handle of the file. More...
 
bool isSequential () const
 Returns true if the file can only be manipulated sequentially; otherwise returns false. More...
 
bool link (const QString &newName)
 Creates a link named linkName that points to the file currently specified by fileName(). More...
 
ucharmap (qint64 offset, qint64 size, MemoryMapFlags flags=NoOptions)
 Maps size bytes of the file into memory starting at offset. More...
 
bool open (OpenMode flags)
 Opens the file using OpenMode mode, returning true if successful; otherwise false. More...
 
bool open (FILE *f, OpenMode flags)
 Opens the existing file handle fh in the given mode. More...
 
bool open (int fd, OpenMode flags)
 Opens the existing file descriptor fd in the given mode. More...
 
bool open (FILE *f, OpenMode ioFlags, FileHandleFlags handleFlags)
 Opens the existing file handle fh in the given mode. More...
 
bool open (int fd, OpenMode ioFlags, FileHandleFlags handleFlags)
 Opens the existing file descriptor fd in the given mode. More...
 
Permissions permissions () const
 Returns the complete OR-ed together combination of QFile::Permission for the file. More...
 
qint64 pos () const
 Reimplemented Function More...
 
 QFile ()
 
 QFile (const QString &name)
 Constructs a new file object to represent the file with the given name. More...
 
 QFile (QObject *parent)
 Constructs a new file object with the given parent. More...
 
 QFile (const QString &name, QObject *parent)
 Constructs a new file object with the given parent to represent the file with the specified name. More...
 
QString readLink () const
 Use symLinkTarget() instead. More...
 
bool remove ()
 Removes the file specified by fileName(). More...
 
bool rename (const QString &newName)
 Renames the file currently specified by fileName() to newName. More...
 
bool resize (qint64 sz)
 Sets the file size (in bytes) sz. More...
 
bool seek (qint64 offset)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setFileName (const QString &name)
 Sets the name of the file. More...
 
bool setPermissions (Permissions permissionSpec)
 Sets the permissions for the file to the permissions specified. More...
 
qint64 size () const
 Returns the size of the file. More...
 
QString symLinkTarget () const
 Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link. More...
 
bool unmap (uchar *address)
 Unmaps the memory address. More...
 
void unsetError ()
 Sets the file's error to QFile::NoError. More...
 
 ~QFile ()
 Destroys the file object, closing it if necessary. More...
 
- Public Functions inherited from QIODevice
virtual qint64 bytesAvailable () const
 Returns the number of bytes that are available for reading. More...
 
virtual qint64 bytesToWrite () const
 For buffered devices, this function returns the number of bytes waiting to be written. More...
 
virtual bool canReadLine () const
 Returns true if a complete line of data can be read from the device; otherwise returns false. More...
 
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
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. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
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. More...
 
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. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) 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. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
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. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static bool copy (const QString &fileName, const QString &newName)
 Copies the file fileName to newName. More...
 
static QString decodeName (const QByteArray &localFileName)
 This does the reverse of QFile::encodeName() using localFileName. More...
 
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. More...
 
static QByteArray encodeName (const QString &fileName)
 By default, this function converts fileName to the local 8-bit encoding determined by the user's locale. More...
 
static bool exists (const QString &fileName)
 Returns true if the file specified by fileName exists; otherwise returns false. More...
 
static bool link (const QString &oldname, const QString &newName)
 Creates a link named linkName that points to the file fileName. More...
 
static Permissions permissions (const QString &filename)
 Returns the complete OR-ed together combination of QFile::Permission for fileName. More...
 
static QString readLink (const QString &fileName)
 Use symLinkTarget() instead. More...
 
static bool remove (const QString &fileName)
 Removes the file specified by the fileName given. More...
 
static bool rename (const QString &oldName, const QString &newName)
 Renames the file oldName to newName. More...
 
static bool resize (const QString &filename, qint64 sz)
 Sets fileName to size (in bytes) sz. More...
 
static void setDecodingFunction (DecoderFn)
 Sets the function for decoding 8-bit file names. More...
 
static void setEncodingFunction (EncoderFn)
 Sets the function for encoding Unicode file names. More...
 
static bool setPermissions (const QString &filename, Permissions permissionSpec)
 Sets the permissions for fileName file to permissions. More...
 
static QString symLinkTarget (const QString &fileName)
 Returns the absolute path of the file 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. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Functions

 QFile (QFilePrivate &dd, QObject *parent=0)
 
qint64 readData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
qint64 readLineData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
qint64 writeData (const char *data, qint64 len)
 Reimplemented Function More...
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QFile class provides an interface for reading from and writing to files.

Note
This class or function is reentrant.

QFile is an I/O device for reading and writing text and binary files and The Qt Resource System{resources}. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.

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

You can check for a file's existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), 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 get the current file position using pos(), or move to a new file position using seek(). If you've reached the end of the file, atEnd() returns true.

Reading Files Directly

The following example reads a text file line by line:

QFile file("in.txt");
return;
while (!file.atEnd()) {
QByteArray line = file.readLine();
process_line(line);
}

The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators ("\\r\\n") into C++-style terminators ("\\n"). By default, QFile assumes binary, i.e. it doesn't perform any conversion on the bytes stored in the file.

Using Streams to Read Files

The next example uses QTextStream to read a text file line by line:

QFile file("in.txt");
return;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
process_line(line);
}

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system's local 8-bit encoding is used (e.g., ISO 8859-1 for most of Europe; see QTextCodec::codecForLocale() for details). This can be changed using setCodec().

To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right:

QFile file("out.txt");
return;
QTextStream out(&file);
out << "The magic number is: " << 49 << "\n";

QDataStream is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.

When you use QFile, QFileInfo, and QDir to access the file system with Qt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to use standard C++ APIs ( <cstdio> or <iostream>) or platform-specific APIs to access files instead of QFile, you can use the encodeName() and decodeName() functions to convert between Unicode file names and 8-bit file names.

On Unix, there are some special system files (e.g. in /proc) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling read(). In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call readAll(), or call 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");
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 that 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 cannot 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, {The Qt Resource System}

Definition at line 65 of file qfile.h.

Typedefs

◆ DecoderFn

QFile::DecoderFn

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

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

Definition at line 124 of file qfile.h.

◆ EncoderFn

QFile::EncoderFn

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

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

Definition at line 123 of file qfile.h.

Enumerations

◆ FileError

This enum describes the errors that may be returned by the error() function.

  • NoError No error occurred.
  • ReadError An error occurred when reading from the file.
  • WriteError An error occurred when writing to the file.
  • FatalError A fatal error occurred.
  • ResourceError
  • OpenError The file could not be opened.
  • AbortError The operation was aborted.
  • TimeOutError A timeout occurred.
  • UnspecifiedError An unspecified error occurred.
  • RemoveError The file could not be removed.
  • RenameError The file could not be renamed.
  • PositionError The position in the file could not be changed.
  • ResizeError The file could not be resized.
  • PermissionsError The file could not be accessed.
  • CopyError The file could not be copied.
  • ConnectError
Enumerator
NoError 
ReadError 
WriteError 
FatalError 
ResourceError 
OpenError 
AbortError 
TimeOutError 
UnspecifiedError 
RemoveError 
RenameError 
PositionError 
ResizeError 
PermissionsError 
CopyError 

Definition at line 74 of file qfile.h.

74  {
75  NoError = 0,
76  ReadError = 1,
77  WriteError = 2,
78  FatalError = 3,
79  ResourceError = 4,
80  OpenError = 5,
81  AbortError = 6,
82  TimeOutError = 7,
83  UnspecifiedError = 8,
84  RemoveError = 9,
85  RenameError = 10,
86  PositionError = 11,
87  ResizeError = 12,
88  PermissionsError = 13,
89  CopyError = 14
90 #ifdef QT3_SUPPORT
91  , ConnectError = 30
92 #endif
93  };

◆ FileHandleFlag

This enum is used when opening a file to specify additional options which only apply to files and not to a generic QIODevice.

Since
4.8
  • AutoCloseHandle The file handle passed into open() should be closed by close(), the default behaviour is that close just flushes the file and the application is responsible for closing the file handle. When opening a file by name, this flag is ignored as Qt always "owns" the file handle and must close it.
  • DontCloseHandle The file handle passed into open() will not be closed by Qt. The application must ensure that close() is called.
Enumerator
AutoCloseHandle 
DontCloseHandle 

Definition at line 103 of file qfile.h.

103  {
104  AutoCloseHandle = 0x0001,
105  DontCloseHandle = 0
106  };

◆ MemoryMapFlags

This enum describes special options that may be used by the map() function.

Since
4.4
  • NoOptions No options.
Enumerator
NoOptions 

Definition at line 180 of file qfile.h.

180  {
181  NoOptions = 0
182  };

◆ Permission

This enum is used by the permission() function to report the permissions and ownership of a file.

The values may be OR-ed together to test multiple permissions and ownership values.

  • ReadOwner The file is readable by the owner of the file.
  • WriteOwner The file is writable by the owner of the file.
  • ExeOwner The file is executable by the owner of the file.
  • ReadUser The file is readable by the user.
  • WriteUser The file is writable by the user.
  • ExeUser The file is executable by the user.
  • ReadGroup The file is readable by the group.
  • WriteGroup The file is writable by the group.
  • ExeGroup The file is executable by the group.
  • ReadOther The file is readable by anyone.
  • WriteOther The file is writable by anyone.
  • ExeOther The file is executable by anyone.
Warning
Because of differences in the platforms supported by Qt, the semantics of ReadUser, WriteUser and ExeUser are platform-dependent: On Unix, the rights of the owner of the file are returned and on Windows the rights of the current user are returned. This behavior might change in a future Qt version.

Note that Qt does not by default check for permissions on NTFS file systems, as this may decrease the performance of file handling considerably. It is possible to force permission checking on NTFS by including the following code in your source:

Permission checking is then turned on and off by incrementing and decrementing qt_ntfs_permission_lookup by 1.

qt_ntfs_permission_lookup++; // turn checking on
qt_ntfs_permission_lookup--; // turn it off again
Enumerator
ReadOwner 
WriteOwner 
ExeOwner 
ReadUser 
WriteUser 
ExeUser 
ReadGroup 
WriteGroup 
ExeGroup 
ReadOther 
WriteOther 
ExeOther 

Definition at line 95 of file qfile.h.

95  {
96  ReadOwner = 0x4000, WriteOwner = 0x2000, ExeOwner = 0x1000,
97  ReadUser = 0x0400, WriteUser = 0x0200, ExeUser = 0x0100,
98  ReadGroup = 0x0040, WriteGroup = 0x0020, ExeGroup = 0x0010,
99  ReadOther = 0x0004, WriteOther = 0x0002, ExeOther = 0x0001
100  };

Constructors and Destructors

◆ QFile() [1/5]

QFile::QFile ( )
Warning
This function is not part of the public interface.

Definition at line 417 of file qfile.cpp.

Referenced by copy(), link(), permissions(), remove(), rename(), resize(), QFilePrivate::setError(), and setPermissions().

418  : QIODevice(*new QFilePrivate, 0)
419 {
420 }
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

◆ QFile() [2/5]

QFile::QFile ( const QString name)

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

Definition at line 431 of file qfile.cpp.

432  : QIODevice(*new QFilePrivate, 0)
433 {
434  Q_D(QFile);
435  d->fileName = name;
436 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
const char * name
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

◆ QFile() [3/5]

QFile::QFile ( QObject parent)
explicit

Constructs a new file object with the given parent.

Definition at line 424 of file qfile.cpp.

425  : QIODevice(*new QFilePrivate, parent)
426 {
427 }
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

◆ QFile() [4/5]

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

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

Definition at line 441 of file qfile.cpp.

442  : QIODevice(*new QFilePrivate, parent)
443 {
444  Q_D(QFile);
445  d->fileName = name;
446 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
const char * name
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

◆ ~QFile()

QFile::~QFile ( )

Destroys the file object, closing it if necessary.

Definition at line 459 of file qfile.cpp.

460 {
461  close();
462 }
virtual void close()
Calls QFile::flush() and closes the file.
Definition: qfile.cpp:1680

◆ QFile() [5/5]

QFile::QFile ( QFilePrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 450 of file qfile.cpp.

451  : QIODevice(dd, parent)
452 {
453 }
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

Functions

◆ atEnd()

bool QFile::atEnd ( ) const
virtual

Returns true if the end of the file has been reached; otherwise returns false.

For regular empty files on Unix (e.g. those in /proc), this function returns true, since the file system reports that the size of such a file is 0. Therefore, you should not depend on atEnd() when reading data from such a file, but rather call read() until no more data can be read.

Reimplemented from QIODevice.

Definition at line 1735 of file qfile.cpp.

Referenced by copy(), QBenchmarkValgrindUtils::extractResult(), fontFile(), QHostInfo::localDomainName(), qt_parseEtcLpPrinters(), qt_parseNsswitchConf(), qt_parsePrintcap(), qt_parsePrintersConf(), and QCoreApplicationData::~QCoreApplicationData().

1736 {
1737  Q_D(const QFile);
1738 
1739  // If there's buffered data left, we're not at the end.
1740  if (!d->buffer.isEmpty())
1741  return false;
1742 
1743  if (!isOpen())
1744  return true;
1745 
1746  if (!d->ensureFlushed())
1747  return false;
1748 
1749  // If the file engine knows best, say what it says.
1750  if (d->fileEngine->supportsExtension(QAbstractFileEngine::AtEndExtension)) {
1751  // Check if the file engine supports AtEndExtension, and if it does,
1752  // check if the file engine claims to be at the end.
1753  return d->fileEngine->atEnd();
1754  }
1755 
1756  // if it looks like we are at the end, or if size is not cached,
1757  // fall through to bytesAvailable() to make sure.
1758  if (pos() < d->cachedSize)
1759  return false;
1760 
1761  // Fall back to checking how much is available (will stat files).
1762  return bytesAvailable() == 0;
1763 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
qint64 pos() const
Reimplemented Function
Definition: qfile.cpp:1720
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752

◆ close()

void QFile::close ( )
virtual

Calls QFile::flush() and closes the file.

Errors from flush are ignored.

See also
QIODevice::close()

Reimplemented from QIODevice.

Definition at line 1680 of file qfile.cpp.

Referenced by QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QUnixPrintWidgetPrivate::checkFields(), QNetworkAccessFileBackend::closeDownstreamChannel(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QTemporaryFile::createLocalFile(), QNetworkDiskCache::data(), QGraphicsAnchorLayoutPrivate::dumpGraph(), QPdfEnginePrivate::embedFont(), QtopiaPrintEngine::end(), QZipReader::extractAll(), QNetworkDiskCache::fileMetaData(), fontPath(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), QTransportAuthPrivate::getClientKey(), QScriptEngine::importExtension(), QAxScriptManager::load(), QTextBrowser::loadResource(), QTextDocument::loadResource(), QPictureIO::pictureFormat(), qt_parse_pattern(), QPictureIO::read(), registerFont(), remove(), rename(), setFileName(), QSslSocketBackendPrivate::startHandshake(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QPictureIO::write(), QCoreApplicationData::~QCoreApplicationData(), ~QFile(), and QTemporaryFile::~QTemporaryFile().

1681 {
1682  Q_D(QFile);
1683  if(!isOpen())
1684  return;
1685  bool flushed = flush();
1686  QIODevice::close();
1687 
1688  // reset write buffer
1689  d->lastWasWrite = false;
1690  d->writeBuffer.clear();
1691 
1692  // keep earlier error from flush
1693  if (d->fileEngine->close() && flushed)
1694  unsetError();
1695  else if (flushed)
1696  d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1697 }
double d
Definition: qnumeric_p.h:62
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
Definition: qiodevice.cpp:590
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
bool flush()
Flushes any buffered data to the file.
Definition: qfile.cpp:1645
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ copy() [1/2]

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.

Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it).

The source file is closed before it is copied.

See also
setFileName()

Definition at line 926 of file qfile.cpp.

Referenced by QDragManager::drag(), QDirModel::dropMimeData(), and QFileSystemModel::dropMimeData().

927 {
928  Q_D(QFile);
929  if (d->fileName.isEmpty()) {
930  qWarning("QFile::copy: Empty or null file name");
931  return false;
932  }
933  if (QFile(newName).exists()) {
934  // ### Race condition. If a file is moved in after this, it /will/ be
935  // overwritten. On Unix, the proper solution is to use hardlinks:
936  // return ::link(old, new) && ::remove(old); See also rename().
937  d->setError(QFile::CopyError, tr("Destination file exists"));
938  return false;
939  }
940  unsetError();
941  close();
942  if(error() == QFile::NoError) {
943  if(fileEngine()->copy(newName)) {
944  unsetError();
945  return true;
946  } else {
947  bool error = false;
948  if(!open(QFile::ReadOnly)) {
949  error = true;
950  d->setError(QFile::CopyError, tr("Cannot open %1 for input").arg(d->fileName));
951  } else {
952  QString fileTemplate = QLatin1String("%1/qt_temp.XXXXXX");
953 #ifdef QT_NO_TEMPORARYFILE
954  QFile out(fileTemplate.arg(QFileInfo(newName).path()));
955  if (!out.open(QIODevice::ReadWrite))
956  error = true;
957 #else
958  QTemporaryFile out(fileTemplate.arg(QFileInfo(newName).path()));
959  if (!out.open()) {
960  out.setFileTemplate(fileTemplate.arg(QDir::tempPath()));
961  if (!out.open())
962  error = true;
963  }
964 #endif
965  if (error) {
966  out.close();
967  close();
968  d->setError(QFile::CopyError, tr("Cannot open for output"));
969  } else {
970  char block[4096];
971  qint64 totalRead = 0;
972  while(!atEnd()) {
973  qint64 in = read(block, sizeof(block));
974  if (in <= 0)
975  break;
976  totalRead += in;
977  if(in != out.write(block, in)) {
978  close();
979  d->setError(QFile::CopyError, tr("Failure to write block"));
980  error = true;
981  break;
982  }
983  }
984 
985  if (totalRead != size()) {
986  // Unable to read from the source. The error string is
987  // already set from read().
988  error = true;
989  }
990  if (!error && !out.rename(newName)) {
991  error = true;
992  close();
993  d->setError(QFile::CopyError, tr("Cannot create %1 for output").arg(newName));
994  }
995 #ifdef QT_NO_TEMPORARYFILE
996  if (error)
997  out.remove();
998 #else
999  if (!error)
1000  out.setAutoRemove(false);
1001 #endif
1002  }
1003  }
1004  if(!error) {
1005  QFile::setPermissions(newName, permissions());
1006  close();
1007  unsetError();
1008  return true;
1009  }
1010  }
1011  }
1012  return false;
1013 }
double d
Definition: qnumeric_p.h:62
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition: qfile.cpp:1064
The QTemporaryFile class is an I/O device that operates on temporary files.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
bool exists() const
Returns true if the file specified by fileName() exists; otherwise returns false. ...
Definition: qfile.cpp:626
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
static QString tempPath()
Returns the absolute path of the system&#39;s temporary directory.
Definition: qdir.cpp:1987
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const Q_REQUIRED_RESULT
Definition: qstring.cpp:7186
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
Definition: qfile.cpp:1605
QFile()
Definition: qfile.cpp:417
bool copy(const QString &newName)
Copies the file currently specified by fileName() to a file called newName.
Definition: qfile.cpp:926
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
Definition: qfile.cpp:1574
void setFileTemplate(const QString &name)
Sets the static portion of the file name to name.
FileError error() const
Returns the file error status.
Definition: qfile.cpp:1984
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
bool atEnd() const
Returns true if the end of the file has been reached; otherwise returns false.
Definition: qfile.cpp:1735
virtual void close()
Calls QFile::flush() and closes the file.
Definition: qfile.cpp:1680

◆ copy() [2/2]

bool QFile::copy ( const QString fileName,
const QString newName 
)
static

Copies the file fileName to newName.

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 successful; otherwise returns false.

If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).

See also
rename()

Definition at line 1031 of file qfile.cpp.

1032 {
1033  return QFile(fileName).copy(newName);
1034 }
QFile()
Definition: qfile.cpp:417

◆ decodeName() [1/2]

QString QFile::decodeName ( const QByteArray localFileName)
static

◆ decodeName() [2/2]

QString QFile::decodeName ( const char *  localFileName)
inlinestatic

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.

See encodeName() for details.

Definition at line 127 of file qfile.h.

128  { return decodeName(QByteArray(localFileName)); }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static QString decodeName(const QByteArray &localFileName)
This does the reverse of QFile::encodeName() using localFileName.
Definition: qfile.cpp:552

◆ encodeName()

QByteArray QFile::encodeName ( const QString fileName)
static

By default, this function 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()

Definition at line 528 of file qfile.cpp.

Referenced by QProcessPrivate::_q_notified(), QInotifyFileSystemWatcherEngine::addPaths(), QKqueueFileSystemWatcherEngine::addPaths(), QZipWriter::addSymLink(), QSharedMemoryPrivate::attach(), QSystemSemaphorePrivate::cleanHandle(), QFontEngineQPF::cleanUpAfterClientCrash(), QSharedMemoryPrivate::create(), QProcessPrivate::createChannel(), QFileSystemEngine::createDirectory(), QSharedMemoryPrivate::createUnixKeyFile(), QSharedMemoryPrivate::detach(), QTranslatorPrivate::do_load(), QFileSystemEngine::getLinkTarget(), QSystemSemaphorePrivate::handle(), QSharedMemoryPrivate::handle(), initializeDb(), QLibraryPrivate::isPlugin(), QLibraryPrivate::load_sys(), QFileDialogPrivate::maxNameLength(), QSQLite2Driver::open(), QWSSoundServerPrivate::openFile(), QBasicUnixFontDatabase::populateFontDatabase(), QPlatformFontDatabase::populateFontDatabase(), QFontEngineQPA::QFontEngineQPA(), QFontEngineQPF::QFontEngineQPF(), QFontEngineQPF1::QFontEngineQPF1(), qt_parse_pattern(), registerFont(), QDynamicFileResourceRoot::registerSelf(), QFileSystemEngine::removeDirectory(), QFileSystemEntry::resolveNativeFilePath(), QPluginLoader::setFileName(), QProcessPrivate::startDetached(), and QProcessPrivate::startProcess().

529 {
530  return (*QFilePrivate::encoder)(fileName);
531 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
static QFile::EncoderFn encoder
Definition: qfile_p.h:93

◆ error()

QFile::FileError QFile::error ( ) const

Returns the file error status.

The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed.

See also
unsetError()

Definition at line 1984 of file qfile.cpp.

Referenced by copy(), QIODevice::errorString(), fontPath(), QPdfBaseEngine::newPage(), QZipReader::QZipReader(), QZipWriter::QZipWriter(), QNetworkAccessFileBackend::readMoreFromFile(), remove(), rename(), and QNetworkDiskCachePrivate::storeItem().

1985 {
1986  Q_D(const QFile);
1987  return d->error;
1988 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ exists() [1/2]

bool QFile::exists ( ) const

Returns true if the file specified by fileName() exists; otherwise returns false.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
fileName(), setFileName()

Definition at line 626 of file qfile.cpp.

Referenced by QFileDialogPrivate::_q_createDirectory(), QDeclarativeImportDatabase::addImportPath(), QDeclarativeImportDatabase::addPluginPath(), QCoreApplicationPrivate::appendApplicationPathToLibraryPaths(), QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QSharedMemoryPrivate::createUnixKeyFile(), QZipWriter::exists(), QZipReader::exists(), QDir::exists(), QZipReader::extractAll(), QLibraryInfoPrivate::findConfiguration(), fontPath(), QDirectFBPixmapData::fromFile(), QDirectFbBlitterPlatformPixmap::fromFile(), QTransportAuthPrivate::getClientKey(), QGtkStylePrivate::getThemeName(), QSharedMemoryPrivate::handle(), QAxBase::initialize(), initializeDb(), isDirPath(), launchWebBrowser(), QCoreApplication::libraryPaths(), QLibraryPrivate::load_sys(), QFontDatabasePrivate::loadFromCache(), loadSingleEngine(), QNetworkAccessFileBackend::open(), QBasicUnixFontDatabase::populateFontDatabase(), QPlatformFontDatabase::populateFontDatabase(), QIconTheme::QIconTheme(), qmlsqldatabase_open_sync(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QDynamicFileResourceRoot::registerSelf(), rename(), QDir::rename(), QNetworkDiskCachePrivate::storeItem(), QConfFileSettingsPrivate::syncConfFile(), QFileDialogPrivate::typedFiles(), and QAxFactory::validateLicenseKey().

627 {
628  // 0x1000000 = QAbstractFileEngine::Refresh, forcing an update
629  return (fileEngine()->fileFlags(QAbstractFileEngine::FlagsMask
631 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
FileFlag
The permissions and types of a file, suitable for OR&#39;ing together.

◆ exists() [2/2]

bool QFile::exists ( const QString fileName)
static

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

Definition at line 639 of file qfile.cpp.

640 {
641  return QFileInfo(fileName).exists();
642 }
bool exists() const
Returns true if the file exists; otherwise returns false.
Definition: qfileinfo.cpp:675
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60

◆ fileEngine()

QAbstractFileEngine * QFile::fileEngine ( ) const
virtual

Returns the QIOEngine for this QFile object.

Warning
This function is not part of the public interface.

Reimplemented in QTemporaryFile.

Definition at line 1965 of file qfile.cpp.

Referenced by QFontDatabase::addApplicationFont(), copy(), QTemporaryFile::createLocalFile(), exists(), fileName(), QFreetypeFace::getFace(), link(), map(), open(), permissions(), readLink(), remove(), rename(), resize(), setPermissions(), size(), and unmap().

1966 {
1967  Q_D(const QFile);
1968  if(!d->fileEngine)
1969  d->fileEngine = QAbstractFileEngine::create(d->fileName);
1970  return d->fileEngine;
1971 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
static QAbstractFileEngine * create(const QString &fileName)
Creates and returns a QAbstractFileEngine suitable for processing fileName.
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ fileName()

QString QFile::fileName ( ) const

◆ flush()

bool QFile::flush ( )

Flushes any buffered data to the file.

Returns true if successful; otherwise returns false.

Definition at line 1645 of file qfile.cpp.

Referenced by close(), QTextStreamPrivate::flushWriteBuffer(), registerFont(), QNetworkAccessFileBackend::uploadReadyReadSlot(), and writeData().

1646 {
1647  Q_D(QFile);
1648  if (!d->fileEngine) {
1649  qWarning("QFile::flush: No file engine. Is IODevice open?");
1650  return false;
1651  }
1652 
1653  if (!d->writeBuffer.isEmpty()) {
1654  qint64 size = d->writeBuffer.size();
1655  if (_qfile_writeData(d->fileEngine, &d->writeBuffer) != size) {
1656  QFile::FileError err = d->fileEngine->error();
1657  if(err == QFile::UnspecifiedError)
1658  err = QFile::WriteError;
1659  d->setError(err, d->fileEngine->errorString());
1660  return false;
1661  }
1662  }
1663 
1664  if (!d->fileEngine->flush()) {
1665  QFile::FileError err = d->fileEngine->error();
1666  if(err == QFile::UnspecifiedError)
1667  err = QFile::WriteError;
1668  d->setError(err, d->fileEngine->errorString());
1669  return false;
1670  }
1671  return true;
1672 }
double d
Definition: qnumeric_p.h:62
static qint64 _qfile_writeData(QAbstractFileEngine *engine, QRingBuffer *buffer)
Definition: qfile.cpp:1631
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
FileError
This enum describes the errors that may be returned by the error() function.
Definition: qfile.h:74

◆ handle()

int QFile::handle ( ) const

Returns the file handle of the file.

This is a small positive integer, suitable for use with C library functions such as fdopen() and fcntl(). On systems that use file descriptors for sockets (i.e. Unix systems, but not Windows) the handle can be used with QSocketNotifier as well.

If the file is not open, or there is an error, handle() returns -1.

This function is not supported on Windows CE.

On Symbian, this function returns -1 if the file was opened normally, as Symbian OS native file handles do not fit in an int, and are incompatible with C library functions that the handle would be used for. If the file was opened using the overloads that take an open C library file handle / file descriptor, then this function returns that same handle.

See also
QSocketNotifier

Definition at line 1419 of file qfile.cpp.

Referenced by QTextStreamPrivate::fillReadBuffer(), QPatternist::ColorOutputPrivate::isColoringPossible(), and QConfFileSettingsPrivate::syncConfFile().

1420 {
1421  Q_D(const QFile);
1422  if (!isOpen() || !d->fileEngine)
1423  return -1;
1424 
1425  return d->fileEngine->handle();
1426 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ isSequential()

bool QFile::isSequential ( ) const
virtual

Returns true if the file can only be manipulated sequentially; otherwise returns false.

Most files support random-access, but some special files may not.

See also
QIODevice::isSequential()

Reimplemented from QIODevice.

Definition at line 1044 of file qfile.cpp.

Referenced by QFilePrivate::putCharHelper(), and rename().

1045 {
1046  Q_D(const QFile);
1047  return d->fileEngine && d->fileEngine->isSequential();
1048 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ link() [1/2]

bool QFile::link ( const QString linkName)

Creates a link named linkName that points to the file currently specified by fileName().

What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

This function will not overwrite an already existing entity in the file system; in this case, link() will return false and set QFile::error() to return QFile::RenameError.

Note
To create a valid link on Windows, linkName must have a .lnk file extension.
Symbian filesystem does not support links.
See also
setFileName()

Definition at line 877 of file qfile.cpp.

Referenced by QDirModel::dropMimeData(), QFileSystemModel::dropMimeData(), and QZipReader::extractAll().

878 {
879  Q_D(QFile);
880  if (d->fileName.isEmpty()) {
881  qWarning("QFile::link: Empty or null file name");
882  return false;
883  }
884  QFileInfo fi(linkName);
885  if(fileEngine()->link(fi.absoluteFilePath())) {
886  unsetError();
887  return true;
888  }
889  d->setError(QFile::RenameError, d->fileEngine->errorString());
890  return false;
891 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
bool link(const QString &newName)
Creates a link named linkName that points to the file currently specified by fileName().
Definition: qfile.cpp:877

◆ link() [2/2]

bool QFile::link ( const QString fileName,
const QString linkName 
)
static

Creates a link named linkName that points to the file fileName.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

See also
link()

Definition at line 908 of file qfile.cpp.

909 {
910  return QFile(fileName).link(linkName);
911 }
QFile()
Definition: qfile.cpp:417

◆ map()

uchar * QFile::map ( qint64  offset,
qint64  size,
MemoryMapFlags  flags = NoOptions 
)

Maps size bytes of the file into memory starting at offset.

Since
4.4 A file should be open for a map to succeed but the file does not need to stay open after the memory has been mapped. When the QFile is destroyed or a new file is opened with this object, any maps that have not been unmapped will automatically be unmapped.

Any mapping options can be passed through flags.

Returns a pointer to the memory or 0 if there is an error.

Note
On Windows CE 5.0 the file will be closed before mapping occurs.
See also
unmap(), QAbstractFileEngine::supportsExtension()

Definition at line 1460 of file qfile.cpp.

Referenced by QNetworkDiskCache::data(), and qt_parse_pattern().

1461 {
1462  Q_D(QFile);
1463  if (fileEngine()
1464  && d->fileEngine->supportsExtension(QAbstractFileEngine::MapExtension)) {
1465  unsetError();
1466  uchar *address = d->fileEngine->map(offset, size, flags);
1467  if (address == 0)
1468  d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1469  return address;
1470  }
1471  return 0;
1472 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
unsigned char uchar
Definition: qglobal.h:994
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ open() [1/5]

bool QFile::open ( OpenMode  mode)
virtual

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.

Note
In QIODevice::WriteOnly or QIODevice::ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.
See also
QIODevice::OpenMode, setFileName()

Reimplemented from QIODevice.

Reimplemented in QTemporaryFile.

Definition at line 1064 of file qfile.cpp.

Referenced by __fileOpen(), QFontDatabase::addApplicationFont(), QTransportAuth::authorizeRequest(), QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QUnixPrintWidgetPrivate::checkFields(), QPatternist::ColorOutputPrivate::ColorOutputPrivate(), compileSource(), QGLShader::compileSourceFile(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QTemporaryFile::createLocalFile(), createPixmapDataSync(), QUuid::createUuid(), QNetworkDiskCache::data(), QTranslatorPrivate::do_load(), QGraphicsAnchorLayoutPrivate::dumpGraph(), DumpIDL(), dumpOutput(), QPdfEnginePrivate::embedFont(), QtopiaPrintEngine::end(), QZipReader::extractAll(), QBenchmarkValgrindUtils::extractResult(), QNetworkDiskCache::fileMetaData(), fontFile(), fontPath(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), QSslCertificate::fromPath(), QFreetypeFace::getFace(), QGtkStylePrivate::getThemeName(), QImageReader::imageFormat(), QScriptEngine::importExtension(), QDeclarativeInclude::include(), QCss::Parser::init(), QImageReaderPrivate::initHandler(), initializeDb(), QConfFile::isWritable(), launchWebBrowser(), QPicture::load(), QSvgTinyDocument::load(), QDeclarativeBorderImage::load(), QDeclarativeDataLoader::load(), QAxScriptManager::load(), QFontDatabasePrivate::loadFromCache(), QRawFont::loadFromFile(), QWSKbPrivate::loadKeymap(), QTextBrowser::loadResource(), QTextDocument::loadResource(), QScriptDebuggerConsolePrivate::loadScriptedCommands(), QHostInfo::localDomainName(), FAREnforcer::logAuthAttempt(), QNetworkAccessFileBackend::open(), QTemporaryFile::open(), open(), QFileOpenEvent::openFile(), QPdfBaseEnginePrivate::openPrintDevice(), operator<<(), QDeclarativeDirParser::parse(), QPatternist::XsdSchemaParser::parseImport(), QPictureIO::pictureFormat(), QDeclarativePixmapReader::processJob(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), qt_getDefaultFromHomePrinters(), qt_getLprPrinters(), qt_parse_pattern(), qt_parseEtcLpPrinters(), qt_parseNsswitchConf(), qt_parsePrintcap(), qt_parsePrintersConf(), qt_parseQconfig(), QTextStream::QTextStream(), QZipReader::QZipReader(), QZipWriter::QZipWriter(), QPictureIO::read(), QWSCalibratedMouseHandler::readCalibration(), readConf(), readSourceFile(), registerFont(), QDynamicFileResourceRoot::registerSelf(), rename(), runningUnderDebugger(), QPicture::save(), QWaylandSelection::send(), QSslSocket::setLocalCertificate(), QSslSocket::setPrivateKey(), QTransportAuth::setProcessKey(), QSslSocketBackendPrivate::startHandshake(), QConfFileSettingsPrivate::syncConfFile(), QDeclarativeInclude::worker_include(), QSvgIconEngine::write(), QPictureIO::write(), QWSCalibratedMouseHandler::writeCalibration(), writeIncludeFile(), QCoreApplicationData::~QCoreApplicationData(), and QTraceWindowSurface::~QTraceWindowSurface().

1065 {
1066  Q_D(QFile);
1067  if (isOpen()) {
1068  qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
1069  return false;
1070  }
1071  if (mode & Append)
1072  mode |= WriteOnly;
1073 
1074  unsetError();
1075  if ((mode & (ReadOnly | WriteOnly)) == 0) {
1076  qWarning("QIODevice::open: File access not specified");
1077  return false;
1078  }
1079 
1080 #ifdef Q_OS_SYMBIAN
1081  // For symbian, the unbuffered flag is used to control write-behind cache behaviour
1082  if (fileEngine()->open(mode))
1083 #else
1084  // QIODevice provides the buffering, so there's no need to request it from the file engine.
1085  if (fileEngine()->open(mode | QIODevice::Unbuffered))
1086 #endif
1087  {
1088  QIODevice::open(mode);
1089  if (mode & Append) {
1090  //The file engine should have done this in open(),
1091  //this is a workaround for backward compatibility
1092  fileEngine()->seek(size());
1093  }
1094  return true;
1095  }
1096  QFile::FileError err = d->fileEngine->error();
1097  if(err == QFile::UnspecifiedError)
1098  err = QFile::OpenError;
1099  d->setError(err, d->fileEngine->errorString());
1100  return false;
1101 }
double d
Definition: qnumeric_p.h:62
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition: qfile.cpp:1064
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
virtual bool seek(qint64 pos)
Sets the file position to the given offset.
Q_CORE_EXPORT void qWarning(const char *,...)
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
FileError
This enum describes the errors that may be returned by the error() function.
Definition: qfile.h:74
#define qPrintable(string)
Definition: qglobal.h:1750

◆ open() [2/5]

bool QFile::open ( FILE *  fh,
OpenMode  mode 
)

Opens the existing file handle fh in the given mode.

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 successful; otherwise returns false.

Example:

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

When a QFile is opened using this function, close() does not actually close the file, but only flushes it.

Warning:

  1. If fh does not refer to a regular file, e.g., it is stdin, stdout, or stderr, you may not be able to seek(). size() returns 0 in those cases. See QIODevice::isSequential() for more information.
  2. Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
Note
For Windows CE you may not be able to call resize().
See also
close(), {qmake Variable Reference::CONFIG}{qmake Variable Reference}

Note for the Windows Platform

fh must be opened in binary mode (i.e., the mode string must contain 'b', as in "rb" or "wb") when accessing files and other random-access devices. Qt 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. To do this, add the following declaration to your application's project file:

CONFIG += console

Definition at line 1152 of file qfile.cpp.

1153 {
1154  return open(fh, mode, DontCloseHandle);
1155 }
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition: qfile.cpp:1064

◆ open() [3/5]

bool QFile::open ( int  fd,
OpenMode  mode 
)

Opens the existing file descriptor fd in the given mode.

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 successful; otherwise returns false.

When a QFile is opened using this function, close() does not actually close the file.

The QFile that is opened using this function 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. See QIODevice::isSequential() for more information.
For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns 0.
Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
See also
close()

Definition at line 1270 of file qfile.cpp.

1271 {
1272  return open(fd, mode, DontCloseHandle);
1273 }
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition: qfile.cpp:1064

◆ open() [4/5]

bool QFile::open ( FILE *  fh,
OpenMode  mode,
FileHandleFlags  handleFlags 
)

Opens the existing file handle fh in the given mode.

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 successful; otherwise returns false.

Example:

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

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

Warning:

  1. If fh does not refer to a regular file, e.g., it is stdin, stdout, or stderr, you may not be able to seek(). size() returns 0 in those cases. See QIODevice::isSequential() for more information.
  2. Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
Note
For Windows CE you may not be able to call resize().
See also
close(), {qmake Variable Reference::CONFIG}{qmake Variable Reference}

Note for the Windows Platform

fh must be opened in binary mode (i.e., the mode string must contain 'b', as in "rb" or "wb") when accessing files and other random-access devices. Qt 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. To do this, add the following declaration to your application's project file:

CONFIG += console

Definition at line 1203 of file qfile.cpp.

1204 {
1205  Q_D(QFile);
1206  if (isOpen()) {
1207  qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
1208  return false;
1209  }
1210  if (mode & Append)
1211  mode |= WriteOnly;
1212  unsetError();
1213  if ((mode & (ReadOnly | WriteOnly)) == 0) {
1214  qWarning("QFile::open: File access not specified");
1215  return false;
1216  }
1217  if (d->openExternalFile(mode, fh, handleFlags)) {
1218  QIODevice::open(mode);
1219  if (mode & Append) {
1220  seek(size());
1221  } else {
1222  qint64 pos = (qint64)QT_FTELL(fh);
1223  if (pos != -1)
1224  seek(pos);
1225  }
1226  return true;
1227  }
1228  return false;
1229 }
double d
Definition: qnumeric_p.h:62
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
Q_CORE_EXPORT void qWarning(const char *,...)
qint64 pos() const
Reimplemented Function
Definition: qfile.cpp:1720
__int64 qint64
Definition: qglobal.h:942
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
#define qPrintable(string)
Definition: qglobal.h:1750
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qfile.cpp:1784

◆ open() [5/5]

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

Opens the existing file descriptor fd in the given mode.

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 successful; otherwise returns false.

When a QFile is opened using this function, behaviour of close() is controlled by the handleFlags argument. If AutoCloseHandle is specified, and this function 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 function 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. See QIODevice::isSequential() for more information.
For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns 0.
Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
See also
close()

Definition at line 1308 of file qfile.cpp.

1309 {
1310  Q_D(QFile);
1311  if (isOpen()) {
1312  qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
1313  return false;
1314  }
1315  if (mode & Append)
1316  mode |= WriteOnly;
1317  unsetError();
1318  if ((mode & (ReadOnly | WriteOnly)) == 0) {
1319  qWarning("QFile::open: File access not specified");
1320  return false;
1321  }
1322  if (d->openExternalFile(mode, fd, handleFlags)) {
1323  QIODevice::open(mode);
1324  if (mode & Append) {
1325  seek(size());
1326  } else {
1327  qint64 pos = (qint64)QT_LSEEK(fd, QT_OFF_T(0), SEEK_CUR);
1328  if (pos != -1)
1329  seek(pos);
1330  }
1331  return true;
1332  }
1333  return false;
1334 }
double d
Definition: qnumeric_p.h:62
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
Q_CORE_EXPORT void qWarning(const char *,...)
qint64 pos() const
Reimplemented Function
Definition: qfile.cpp:1720
__int64 qint64
Definition: qglobal.h:942
qint64 size() const
Returns the size of the file.
Definition: qfile.cpp:1707
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
#define qPrintable(string)
Definition: qglobal.h:1750
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qfile.cpp:1784

◆ permissions() [1/2]

QFile::Permissions QFile::permissions ( ) const

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

See also
setPermissions(), setFileName()

Definition at line 1574 of file qfile.cpp.

Referenced by copy(), rename(), and QConfFileSettingsPrivate::syncConfFile().

1575 {
1576  QAbstractFileEngine::FileFlags perms = fileEngine()->fileFlags(QAbstractFileEngine::PermsMask) & QAbstractFileEngine::PermsMask;
1577  return QFile::Permissions((int)perms); //ewww
1578 }
virtual FileFlags fileFlags(FileFlags type=FileInfoAll) const
This function should return the set of OR&#39;d flags that are true for the file engine&#39;s file...
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965

◆ permissions() [2/2]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1591 of file qfile.cpp.

1592 {
1593  return QFile(fileName).permissions();
1594 }
QFile()
Definition: qfile.cpp:417

◆ pos()

qint64 QFile::pos ( ) const
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1720 of file qfile.cpp.

Referenced by atEnd(), QTemporaryFile::createLocalFile(), QNetworkDiskCache::data(), open(), and QFilePrivate::putCharHelper().

1721 {
1722  return QIODevice::pos();
1723 }
virtual qint64 pos() const
For random-access devices, this function returns the position that data is written to or read from...
Definition: qiodevice.cpp:624

◆ readData()

qint64 QFile::readData ( char *  data,
qint64  maxlen 
)
protectedvirtual

Reimplemented Function

Implements QIODevice.

Definition at line 1839 of file qfile.cpp.

1840 {
1841  Q_D(QFile);
1842  unsetError();
1843  if (!d->ensureFlushed())
1844  return -1;
1845 
1846  qint64 read = d->fileEngine->read(data, len);
1847  if(read < 0) {
1848  QFile::FileError err = d->fileEngine->error();
1849  if(err == QFile::UnspecifiedError)
1850  err = QFile::ReadError;
1851  d->setError(err, d->fileEngine->errorString());
1852  }
1853 
1854  if (read < len) {
1855  // failed to read all requested, may be at the end of file, stop caching size so that it's rechecked
1856  d->cachedSize = 0;
1857  }
1858 
1859  return read;
1860 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
FileError
This enum describes the errors that may be returned by the error() function.
Definition: qfile.h:74

◆ readLineData()

qint64 QFile::readLineData ( char *  data,
qint64  maxlen 
)
protectedvirtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1812 of file qfile.cpp.

1813 {
1814  Q_D(QFile);
1815  if (!d->ensureFlushed())
1816  return -1;
1817 
1818  qint64 read;
1819  if (d->fileEngine->supportsExtension(QAbstractFileEngine::FastReadLineExtension)) {
1820  read = d->fileEngine->readLine(data, maxlen);
1821  } else {
1822  // Fall back to QIODevice's readLine implementation if the engine
1823  // cannot do it faster.
1824  read = QIODevice::readLineData(data, maxlen);
1825  }
1826 
1827  if (read < maxlen) {
1828  // failed to read all requested, may be at the end of file, stop caching size so that it's rechecked
1829  d->cachedSize = 0;
1830  }
1831 
1832  return read;
1833 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
virtual qint64 readLineData(char *data, qint64 maxlen)
Reads up to maxSize characters into data and returns the number of characters read.
Definition: qiodevice.cpp:1285
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ readLink() [1/2]

QString QFile::readLink ( ) const

Use symLinkTarget() instead.

Definition at line 671 of file qfile.cpp.

672 {
674 }
virtual QString fileName(FileName file=DefaultName) const
Return the file engine&#39;s current file name in the format specified by file.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965

◆ readLink() [2/2]

QString QFile::readLink ( const QString fileName)
static

Use symLinkTarget() instead.

Definition at line 700 of file qfile.cpp.

701 {
702  return QFileInfo(fileName).readLink();
703 }
QString readLink() const
Use symLinkTarget() instead.
Definition: qfileinfo.cpp:1110
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60

◆ remove() [1/2]

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

Definition at line 715 of file qfile.cpp.

Referenced by QUnixPrintWidgetPrivate::checkFields(), QSystemSemaphorePrivate::cleanHandle(), QBenchmarkValgrindUtils::cleanup(), QFontEngineQPF::cleanUpAfterClientCrash(), QWSServerPrivate::cleanupFonts(), QPdfBaseEnginePrivate::closePrintDevice(), QSharedMemoryPrivate::create(), QSharedMemoryPrivate::detach(), QDirModel::dropMimeData(), DumpIDL(), QNetworkDiskCache::expire(), initializeDb(), QTransportAuth::isDiscoveryMode(), registerFont(), QFileSystemModel::remove(), QDir::remove(), QNetworkDiskCachePrivate::removeFile(), rename(), and QNetworkDiskCachePrivate::storeItem().

716 {
717  Q_D(QFile);
718  if (d->fileName.isEmpty()) {
719  qWarning("QFile::remove: Empty or null file name");
720  return false;
721  }
722  unsetError();
723  close();
724  if(error() == QFile::NoError) {
725  if(fileEngine()->remove()) {
726  unsetError();
727  return true;
728  }
729  d->setError(QFile::RemoveError, d->fileEngine->errorString());
730  }
731  return false;
732 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
FileError error() const
Returns the file error status.
Definition: qfile.cpp:1984
virtual void close()
Calls QFile::flush() and closes the file.
Definition: qfile.cpp:1680

◆ remove() [2/2]

bool QFile::remove ( const QString fileName)
static

Removes the file specified by the fileName given.

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 successful; otherwise returns false.

See also
remove()

Definition at line 748 of file qfile.cpp.

749 {
750  return QFile(fileName).remove();
751 }
QFile()
Definition: qfile.cpp:417

◆ rename() [1/2]

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 (i.e., QFile will not overwrite it).

The file is closed before it is renamed.

See also
setFileName()

Definition at line 766 of file qfile.cpp.

Referenced by QDragManager::drag(), QFileSystemModel::dropMimeData(), initializeDb(), QDir::rename(), and QNetworkDiskCachePrivate::storeItem().

767 {
768  Q_D(QFile);
769  if (d->fileName.isEmpty()) {
770  qWarning("QFile::rename: Empty or null file name");
771  return false;
772  }
773  if (QFile(newName).exists()) {
774  // ### Race condition. If a file is moved in after this, it /will/ be
775  // overwritten. On Unix, the proper solution is to use hardlinks:
776  // return ::link(old, new) && ::remove(old);
777  d->setError(QFile::RenameError, tr("Destination file exists"));
778  return false;
779  }
780  unsetError();
781  close();
782  if(error() == QFile::NoError) {
783  if (fileEngine()->rename(newName)) {
784  unsetError();
785  // engine was able to handle the new name so we just reset it
786  d->fileEngine->setFileName(newName);
787  d->fileName = newName;
788  return true;
789  }
790 
791  if (isSequential()) {
792  d->setError(QFile::RenameError, tr("Will not rename sequential file using block copy"));
793  return false;
794  }
795 
796  QFile out(newName);
797  if (open(QIODevice::ReadOnly)) {
798  if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
799  bool error = false;
800  char block[4096];
801  qint64 bytes;
802  while ((bytes = read(block, sizeof(block))) > 0) {
803  if (bytes != out.write(block, bytes)) {
804  d->setError(QFile::RenameError, out.errorString());
805  error = true;
806  break;
807  }
808  }
809  if (bytes == -1) {
810  d->setError(QFile::RenameError, errorString());
811  error = true;
812  }
813  if(!error) {
814  if (!remove()) {
815  d->setError(QFile::RenameError, tr("Cannot remove source file"));
816  error = true;
817  }
818  }
819  if (error) {
820  out.remove();
821  } else {
822  d->fileEngine->setFileName(newName);
824  unsetError();
825  setFileName(newName);
826  }
827  close();
828  return !error;
829  }
830  close();
831  }
832  d->setError(QFile::RenameError, out.isOpen() ? errorString() : out.errorString());
833  }
834  return false;
835 }
double d
Definition: qnumeric_p.h:62
bool rename(const QString &newName)
Renames the file currently specified by fileName() to newName.
Definition: qfile.cpp:766
bool isSequential() const
Returns true if the file can only be manipulated sequentially; otherwise returns false.
Definition: qfile.cpp:1044
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition: qfile.cpp:1064
QString errorString() const
Returns a human-readable description of the last device error that occurred.
Definition: qiodevice.cpp:1671
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
bool exists() const
Returns true if the file specified by fileName() exists; otherwise returns false. ...
Definition: qfile.cpp:626
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
Definition: qfile.cpp:1605
QFile()
Definition: qfile.cpp:417
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
Definition: qfile.cpp:1574
FileError error() const
Returns the file error status.
Definition: qfile.cpp:1984
virtual void close()
Calls QFile::flush() and closes the file.
Definition: qfile.cpp:1680
void setFileName(const QString &name)
Sets the name of the file.
Definition: qfile.cpp:494

◆ rename() [2/2]

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

Renames the file oldName to newName.

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 successful; otherwise returns false.

If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).

See also
rename()

Definition at line 853 of file qfile.cpp.

854 {
855  return QFile(oldName).rename(newName);
856 }
QFile()
Definition: qfile.cpp:417

◆ resize() [1/2]

bool QFile::resize ( qint64  sz)

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

Definition at line 1528 of file qfile.cpp.

Referenced by QFSFileEnginePrivate::longFileName(), and QConfFileSettingsPrivate::syncConfFile().

1529 {
1530  Q_D(QFile);
1531  if (!d->ensureFlushed())
1532  return false;
1533  fileEngine();
1534  if (isOpen() && d->fileEngine->pos() > sz)
1535  seek(sz);
1536  if(d->fileEngine->setSize(sz)) {
1537  unsetError();
1538  d->cachedSize = sz;
1539  return true;
1540  }
1541  d->cachedSize = 0;
1542  d->setError(QFile::ResizeError, d->fileEngine->errorString());
1543  return false;
1544 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qfile.cpp:1784

◆ resize() [2/2]

bool QFile::resize ( const QString fileName,
qint64  sz 
)
static

Sets fileName to size (in bytes) sz.

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

Definition at line 1561 of file qfile.cpp.

1562 {
1563  return QFile(fileName).resize(sz);
1564 }
QFile()
Definition: qfile.cpp:417

◆ seek()

bool QFile::seek ( qint64  pos)
virtual

For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred.

For sequential devices, the default behavior is to do nothing and return false.

Seeking beyond the end of a file: If the position is beyond the end of a file, then seek() shall not immediately extend the file. If a write is performed at this position, then the file shall be extended. The content of the file between the previous end of file and the newly written data is UNDEFINED and varies between platforms and file systems.

Reimplemented from QIODevice.

Definition at line 1784 of file qfile.cpp.

Referenced by QTemporaryFile::createLocalFile(), QTransportAuthPrivate::getClientKey(), open(), QFilePrivate::putCharHelper(), QPictureIO::read(), resize(), and QConfFileSettingsPrivate::syncConfFile().

1785 {
1786  Q_D(QFile);
1787  if (!isOpen()) {
1788  qWarning("QFile::seek: IODevice is not open");
1789  return false;
1790  }
1791 
1792  if (off == d->pos && off == d->devicePos)
1793  return true; //avoid expensive flush for NOP seek to current position
1794 
1795  if (!d->ensureFlushed())
1796  return false;
1797 
1798  if (!d->fileEngine->seek(off) || !QIODevice::seek(off)) {
1799  QFile::FileError err = d->fileEngine->error();
1800  if(err == QFile::UnspecifiedError)
1801  err = QFile::PositionError;
1802  d->setError(err, d->fileEngine->errorString());
1803  return false;
1804  }
1805  unsetError();
1806  return true;
1807 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
Q_CORE_EXPORT void qWarning(const char *,...)
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
FileError
This enum describes the errors that may be returned by the error() function.
Definition: qfile.h:74
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qiodevice.cpp:659

◆ setDecodingFunction()

void QFile::setDecodingFunction ( DecoderFn  function)
static

Sets the function for decoding 8-bit file names.

Note
This class or function is not reentrant.

The default uses the locale-specific 8-bit encoding.

See also
setEncodingFunction(), decodeName()

Definition at line 606 of file qfile.cpp.

607 {
608  if (!f)
609  f = locale_decode;
611 }
static QString locale_decode(const QByteArray &f)
Definition: qfile.cpp:76
static QFile::DecoderFn decoder
Definition: qfile_p.h:94

◆ setEncodingFunction()

void QFile::setEncodingFunction ( EncoderFn  function)
static

Sets the function for encoding Unicode file names.

Note
This class or function is not reentrant.

The default encodes in the locale-specific 8-bit encoding.

See also
encodeName(), setDecodingFunction()

Definition at line 572 of file qfile.cpp.

573 {
574  if (!f)
575  f = locale_encode;
577 }
static QFile::EncoderFn encoder
Definition: qfile_p.h:93
static QByteArray locale_encode(const QString &f)
Definition: qfile.cpp:64

◆ setFileName()

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.

Example:

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

Note that the directory separator "/" works for all operating systems supported by Qt.

See also
fileName(), QFileInfo, QDir

Definition at line 494 of file qfile.cpp.

Referenced by QMacPasteboardMimeVCard::convertFromMime(), fontPath(), QImageReaderPrivate::initHandler(), QHostInfo::localDomainName(), QNetworkAccessFileBackend::open(), QFileOpenEvent::openFile(), QIconTheme::QIconTheme(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QPictureIO::read(), rename(), and QPictureIO::write().

495 {
496  Q_D(QFile);
497  if (isOpen()) {
498  qWarning("QFile::setFileName: File (%s) is already opened",
499  qPrintable(fileName()));
500  close();
501  }
502  if(d->fileEngine) { //get a new file engine later
503  delete d->fileEngine;
504  d->fileEngine = 0;
505  }
506  d->fileName = name;
507 }
double d
Definition: qnumeric_p.h:62
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
const char * name
Q_CORE_EXPORT void qWarning(const char *,...)
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual void close()
Calls QFile::flush() and closes the file.
Definition: qfile.cpp:1680
#define qPrintable(string)
Definition: qglobal.h:1750

◆ setPermissions() [1/2]

bool QFile::setPermissions ( Permissions  permissions)

Sets the permissions for the file to the permissions specified.

Returns true if successful, or false if the permissions cannot be modified.

See also
permissions(), setFileName()

Definition at line 1605 of file qfile.cpp.

Referenced by copy(), QZipReader::extractAll(), rename(), and QConfFileSettingsPrivate::syncConfFile().

1606 {
1607  Q_D(QFile);
1609  unsetError();
1610  return true;
1611  }
1612  d->setError(QFile::PermissionsError, d->fileEngine->errorString());
1613  return false;
1614 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
Definition: qfile.cpp:1605
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
Definition: qfile.cpp:1574

◆ setPermissions() [2/2]

bool QFile::setPermissions ( const QString fileName,
Permissions  permissions 
)
static

Sets the permissions for fileName file to permissions.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1626 of file qfile.cpp.

1627 {
1628  return QFile(fileName).setPermissions(permissions);
1629 }
QFile()
Definition: qfile.cpp:417
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
Definition: qfile.cpp:1574

◆ size()

qint64 QFile::size ( ) const
virtual

Returns the size of the file.

For regular empty files on Unix (e.g. those in /proc), this function returns 0; the contents of such a file are generated on demand in response to you calling read().

Reimplemented from QIODevice.

Definition at line 1707 of file qfile.cpp.

Referenced by copy(), QNetworkDiskCache::data(), QTranslatorPrivate::do_load(), QNetworkDiskCache::expire(), flush(), open(), qt_parse_pattern(), QDynamicFileResourceRoot::registerSelf(), QCacheItem::size(), and QNetworkDiskCachePrivate::storeItem().

1708 {
1709  Q_D(const QFile);
1710  if (!d->ensureFlushed())
1711  return 0;
1712  d->cachedSize = fileEngine()->size();
1713  return d->cachedSize;
1714 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
#define Q_D(Class)
Definition: qglobal.h:2482
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
virtual qint64 size() const
Returns the size of the file.

◆ symLinkTarget() [1/2]

QString QFile::symLinkTarget ( ) const
inline

Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link.

Since
4.2 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

This name may not represent an existing file; it is only a string. QFile::exists() returns true if the symlink points to an existing file.

See also
fileName() setFileName()

Definition at line 137 of file qfile.h.

137 { return readLink(); }
QString readLink() const
Use symLinkTarget() instead.
Definition: qfile.cpp:671

◆ symLinkTarget() [2/2]

static QString QFile::symLinkTarget ( const QString fileName)
inlinestatic

Returns the absolute path of the file 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.

Since
4.2

This name may not represent an existing file; it is only a string. QFile::exists() returns true if the symlink points to an existing file.

Definition at line 138 of file qfile.h.

138 { return readLink(fileName); }
QString readLink() const
Use symLinkTarget() instead.
Definition: qfile.cpp:671

◆ unmap()

bool QFile::unmap ( uchar address)

Unmaps the memory address.

Since
4.4

Returns true if the unmap succeeds; false otherwise.

See also
map(), QAbstractFileEngine::supportsExtension()

Definition at line 1485 of file qfile.cpp.

1486 {
1487  Q_D(QFile);
1488  if (fileEngine()
1489  && d->fileEngine->supportsExtension(QAbstractFileEngine::UnMapExtension)) {
1490  unsetError();
1491  bool success = d->fileEngine->unmap(address);
1492  if (!success)
1493  d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1494  return success;
1495  }
1496  d->setError(PermissionsError, tr("No file engine available or engine does not support UnMapExtension"));
1497  return false;
1498 }
double d
Definition: qnumeric_p.h:62
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Definition: qfile.cpp:1965
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ unsetError()

void QFile::unsetError ( )

Sets the file's error to QFile::NoError.

See also
error()

Definition at line 1996 of file qfile.cpp.

Referenced by close(), copy(), QIODevice::errorString(), link(), map(), open(), readData(), remove(), rename(), resize(), seek(), setPermissions(), unmap(), and writeData().

1997 {
1998  Q_D(QFile);
1999  d->setError(QFile::NoError);
2000 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ writeData()

qint64 QFile::writeData ( const char *  data,
qint64  len 
)
protectedvirtual

Reimplemented Function

Implements QIODevice.

Definition at line 1923 of file qfile.cpp.

1924 {
1925  Q_D(QFile);
1926  unsetError();
1927  d->lastWasWrite = true;
1928  bool buffered = !(d->openMode & Unbuffered);
1929 
1930  // Flush buffered data if this read will overflow.
1931  if (buffered && (d->writeBuffer.size() + len) > QFILE_WRITEBUFFER_SIZE) {
1932  if (!flush())
1933  return -1;
1934  }
1935 
1936  // Write directly to the engine if the block size is larger than
1937  // the write buffer size.
1938  if (!buffered || len > QFILE_WRITEBUFFER_SIZE) {
1939  qint64 ret = d->fileEngine->write(data, len);
1940  if(ret < 0) {
1941  QFile::FileError err = d->fileEngine->error();
1942  if(err == QFile::UnspecifiedError)
1943  err = QFile::WriteError;
1944  d->setError(err, d->fileEngine->errorString());
1945  }
1946  return ret;
1947  }
1948 
1949  // Write to the buffer.
1950  char *writePointer = d->writeBuffer.reserve(len);
1951  if (len == 1)
1952  *writePointer = *data;
1953  else
1954  ::memcpy(writePointer, data, len);
1955  return len;
1956 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool flush()
Flushes any buffered data to the file.
Definition: qfile.cpp:1645
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
static const int QFILE_WRITEBUFFER_SIZE
Definition: qfile.cpp:62
void unsetError()
Sets the file&#39;s error to QFile::NoError.
Definition: qfile.cpp:1996
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
FileError
This enum describes the errors that may be returned by the error() function.
Definition: qfile.h:74

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