- Qt 6.10
- Qt Core
- C++ Classes
- QFileDevice
- Qt 6.10.2 Reference Documentation

# QFileDevice Class

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

Header: | `#include <QFileDevice>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS Core)` `target_link_libraries(mytarget PRIVATE Qt6::Core)`
qmake: | `QT += core`
Inherits: | QIODevice
Inherited By: | QFile and QSaveFile

- List of all members, including inherited members
- QFileDevice is part of Input/Output and Networking.

Note: All functions in this class are reentrant.

## Public Types

enum | FileError { NoError, ReadError, WriteError, FatalError, ResourceError, …, CopyError }
enum | FileHandleFlag { AutoCloseHandle, DontCloseHandle }
flags | FileHandleFlags
enum | FileTime { FileAccessTime, FileBirthTime, FileMetadataChangeTime, FileModificationTime }
enum | MemoryMapFlag { NoOptions, MapPrivateOption }
flags | MemoryMapFlags
enum | Permission { ReadOwner, WriteOwner, ExeOwner, ReadUser, WriteUser, …, ExeOther }
flags | Permissions

## Public Functions

virtual | ~QFileDevice()
QFileDevice::FileError | error() const
virtual QString | fileName() const
QDateTime | fileTime(QFileDevice::FileTime time) const
bool | flush()
int | handle() const
uchar * | map(qint64 offset, qint64 size, QFileDevice::MemoryMapFlags flags = NoOptions)
virtual QFileDevice::Permissions | permissions() const
virtual bool | resize(qint64 sz)
bool | setFileTime(const QDateTime &newDate, QFileDevice::FileTime fileTime)
virtual bool | setPermissions(QFileDevice::Permissions permissions)
bool | unmap(uchar *address)
void | unsetError()

## Reimplemented Public Functions

virtual bool | atEnd() const override
virtual void | close() override
virtual bool | isSequential() const override
virtual qint64 | pos() const override
virtual bool | seek(qint64 pos) override
virtual qint64 | size() const override

## Reimplemented Protected Functions

virtual qint64 | readData(char *data, qint64 len) override
virtual qint64 | readLineData(char *data, qint64 maxlen) override
virtual qint64 | writeData(const char *data, qint64 len) override

## Macros

`(since 6.8)` | QT_NO_USE_NODISCARD_FILE_OPEN
`(since 6.8)` | QT_USE_NODISCARD_FILE_OPEN

## Detailed Description

QFileDevice is the base class for I/O devices that can read and write text and binary files and resources. QFile offers the main functionality, QFileDevice serves as a base class for sharing functionality with other file devices such as QSaveFile, by providing all the operations that can be done on files that have been opened by QFile or QSaveFile.

See also QFile and QSaveFile.

## Member Type Documentation

### enum QFileDevice::FileError

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

Constant | Value | Description
--- | --- | ---
`QFileDevice::NoError` | `0` | No error occurred.
`QFileDevice::ReadError` | `1` | An error occurred when reading from the file.
`QFileDevice::WriteError` | `2` | An error occurred when writing to the file.
`QFileDevice::FatalError` | `3` | A fatal error occurred.
`QFileDevice::ResourceError` | `4` | Out of resources (e.g., too many open files, out of memory, etc.)
`QFileDevice::OpenError` | `5` | The file could not be opened.
`QFileDevice::AbortError` | `6` | The operation was aborted.
`QFileDevice::TimeOutError` | `7` | A timeout occurred.
`QFileDevice::UnspecifiedError` | `8` | An unspecified error occurred.
`QFileDevice::RemoveError` | `9` | The file could not be removed.
`QFileDevice::RenameError` | `10` | The file could not be renamed.
`QFileDevice::PositionError` | `11` | The position in the file could not be changed.
`QFileDevice::ResizeError` | `12` | The file could not be resized.
`QFileDevice::PermissionsError` | `13` | The file could not be accessed.
`QFileDevice::CopyError` | `14` | The file could not be copied.

### enum QFileDevice::FileHandleFlag
flags QFileDevice::FileHandleFlags

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

Constant | Value | Description
--- | --- | ---
`QFileDevice::AutoCloseHandle` | `0x0001` | The file handle passed into open() should be closed by close(), the default behavior 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.
`QFileDevice::DontCloseHandle` | `0` | If not explicitly closed, the underlying file handle is left open when the QFile object is destroyed.

The FileHandleFlags type is a typedef for QFlags<FileHandleFlag>. It stores an OR combination of FileHandleFlag values.

### enum QFileDevice::FileTime

This enum is used by the fileTime() and setFileTime() functions.

Constant | Value | Description
--- | --- | ---
`QFileDevice::FileAccessTime` | `0` | When the file was most recently accessed (e.g. read or written to).
`QFileDevice::FileBirthTime` | `1` | When the file was created (may not be not supported on UNIX).
`QFileDevice::FileMetadataChangeTime` | `2` | When the file's metadata was last changed.
`QFileDevice::FileModificationTime` | `3` | When the file was most recently modified.

See also setFileTime(), fileTime(), and QFileInfo::fileTime().

### enum QFileDevice::MemoryMapFlag
flags QFileDevice::MemoryMapFlags

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

Constant | Value | Description
--- | --- | ---
`QFileDevice::NoOptions` | `0` | No options.
`QFileDevice::MapPrivateOption` | `0x0001` | The mapped memory will be private, so any modifications will not be visible to other processes and will not be written to disk. Any such modifications will be lost when the memory is unmapped. It is unspecified whether modifications made to the file made after the mapping is created will be visible through the mapped memory. This enum value was introduced in Qt 5.4.

The MemoryMapFlags type is a typedef for QFlags<MemoryMapFlag>. It stores an OR combination of MemoryMapFlag values.

### enum QFileDevice::Permission
flags QFileDevice::Permissions

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.

Constant | Value | Description
--- | --- | ---
`QFileDevice::ReadOwner` | `0x4000` | The file is readable by the owner of the file.
`QFileDevice::WriteOwner` | `0x2000` | The file is writable by the owner of the file.
`QFileDevice::ExeOwner` | `0x1000` | The file is executable by the owner of the file.
`QFileDevice::ReadUser` | `0x0400` | The file is readable by the user.
`QFileDevice::WriteUser` | `0x0200` | The file is writable by the user.
`QFileDevice::ExeUser` | `0x0100` | The file is executable by the user.
`QFileDevice::ReadGroup` | `0x0040` | The file is readable by the group.
`QFileDevice::WriteGroup` | `0x0020` | The file is writable by the group.
`QFileDevice::ExeGroup` | `0x0010` | The file is executable by the group.
`QFileDevice::ReadOther` | `0x0004` | The file is readable by others.
`QFileDevice::WriteOther` | `0x0002` | The file is writable by others.
`QFileDevice::ExeOther` | `0x0001` | The file is executable by others.

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: On NTFS file systems, ownership and permissions checking is disabled by default for performance reasons. To enable it, include the following line:

     extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;

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

Note: Since this is a non-atomic global variable, it is only safe to increment or decrement `qt_ntfs_permission_lookup` before any threads other than the main thread have started or after every thread other than the main thread has ended.

Note: From Qt 6.6 the variable `qt_ntfs_permission_lookup` is deprecated. Please use the following alternatives.

The safe and easy way to manage permission checks is to use the RAII class `QNtfsPermissionCheckGuard`.

     void complexFunction()
     {
         QNtfsPermissionCheckGuard permissionGuard;  // check is enabled

         // do complex things here that need permission check enabled

     }   // as the guard goes out of scope the check is disabled

If you need more fine-grained control, it is possible to manage the permission with the following functions instead:

     qAreNtfsPermissionChecksEnabled();   // check status
     qEnableNtfsPermissionChecks();       // turn checking on
     qDisableNtfsPermissionChecks();      // turn it off again

The Permissions type is a typedef for QFlags<Permission>. It stores an OR combination of Permission values.

## Member Function Documentation

### `[virtual noexcept]` QFileDevice::~QFileDevice()

Destroys the file device, closing it if necessary.

### `[override virtual]` bool QFileDevice::atEnd() const

Reimplements: QIODevice::atEnd() const.

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.

### `[override virtual]` void QFileDevice::close()

Reimplements: QIODevice::close().

Calls QFileDevice::flush() and closes the file. Errors from flush are ignored.

See also QIODevice::close().

### QFileDevice::FileError QFileDevice::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().

### `[virtual]` QString QFileDevice::fileName() const

Returns the name of the file. The default implementation in QFileDevice returns a null string.

### QDateTime QFileDevice::fileTime(QFileDevice::FileTime time) const

Returns the file time specified by time. If the time cannot be determined return QDateTime() (an invalid date time).

See also setFileTime(), FileTime, and QDateTime::isValid().

### bool QFileDevice::flush()

Flushes any buffered data to the file. Returns `true` if successful; otherwise returns `false`.

### int QFileDevice::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.

See also QSocketNotifier.

### `[override virtual]` bool QFileDevice::isSequential() const

Reimplements: QIODevice::isSequential() const.

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

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

Maps size bytes of the file into memory starting at offset. 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.

The mapping will have the same open mode as the file (read and/or write), except when using MapPrivateOption, in which case it is always possible to write to the mapped memory.

Any mapping options can be passed through flags.

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

See also unmap().

### `[virtual]` QFileDevice::Permissions QFileDevice::permissions() const

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

See also setPermissions().

### `[override virtual]` qint64 QFileDevice::pos() const

Reimplements: QIODevice::pos() const.

### `[override virtual protected]` qint64 QFileDevice::readData(char *data, qint64 len)

Reimplements: QIODevice::readData(char *data, qint64 maxSize).

### `[override virtual protected]` qint64 QFileDevice::readLineData(char *data, qint64 maxlen)

Reimplements: QIODevice::readLineData(char *data, qint64 maxSize).

### `[virtual]` bool QFileDevice::resize(qint64 sz)

Sets the file size (in bytes) sz. Returns `true` 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.

Warning: This function can fail if the file doesn't exist.

See also size().

### `[override virtual]` bool QFileDevice::seek(qint64 pos)

Reimplements: QIODevice::seek(qint64 pos).

For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. 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() will not immediately extend the file. If a write is performed at this position, then the file will 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.

### bool QFileDevice::setFileTime(const QDateTime &newDate, QFileDevice::FileTime fileTime)

Sets the file time specified by fileTime to newDate, returning true if successful; otherwise returns false.

Note: The file must be open to use this function.

See also fileTime() and FileTime.

### `[virtual]` bool QFileDevice::setPermissions(QFileDevice::Permissions permissions)

Sets the permissions for the file to the permissions specified. Returns `true` if successful, or `false` if the permissions cannot be modified.

Warning: This function does not manipulate ACLs, which may limit its effectiveness.

See also permissions().

### `[override virtual]` qint64 QFileDevice::size() const

Reimplements: QIODevice::size() const.

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

### bool QFileDevice::unmap(uchar *address)

Unmaps the memory address.

Returns `true` if the unmap succeeds; false otherwise.

See also map().

### void QFileDevice::unsetError()

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

See also error().

### `[override virtual protected]` qint64 QFileDevice::writeData(const char *data, qint64 len)

Reimplements: QIODevice::writeData(const char *data, qint64 maxSize).

## Macro Documentation

### `[since 6.8]` QT_NO_USE_NODISCARD_FILE_OPEN

### `[since 6.8]` QT_USE_NODISCARD_FILE_OPEN

File-related I/O classes (such as QFile, QSaveFile, QTemporaryFile) have an `open()` method to open the file they act upon. It is important to check the return value of the call to `open()` before proceeding with reading or writing data into the file.

For this reason, starting with Qt 6.8, some overloads of `open()` have been marked with the `[[nodiscard]]` attribute. Since this change may raise warnings in existing codebases, user code can opt-in or opt-out from having the attribute applied by defining certain macros:

- If the `QT_USE_NODISCARD_FILE_OPEN` macro is defined, overloads of `open()` are marked as `[[nodiscard]]`.
- If the `QT_NO_USE_NODISCARD_FILE_OPEN` is defined, the overloads of `open()` are not marked as `[[nodiscard]]`.
- If neither macro is defined, then the default up to and including Qt 6.9 is not to have the attribute. Starting from Qt 6.10, the attribute is automatically applied.
- If both macros are defined, the program is ill-formed.

These macros were introduced in Qt 6.8.