Qfile как пользоваться
Перейти к содержимому

Qfile как пользоваться

  • автор:

QFile Class

Note: All functions in this class are reentrant.

Public Functions

Reimplemented Public Functions

virtual QString fileName() const override
virtual bool open(QIODeviceBase::OpenMode mode) override
virtual QFileDevice::Permissions permissions() const override
virtual bool resize(qint64 sz) override
virtual bool setPermissions(QFileDevice::Permissions permissions) override
virtual qint64 size() const override

Static Public Members

bool copy(const QString &fileName, const QString &newName)
QString decodeName(const QByteArray &localFileName)
QString decodeName(const char *localFileName)
QByteArray encodeName(const QString &fileName)
bool exists(const QString &fileName)
std::filesystem::path filesystemSymLinkTarget(const std::filesystem::path &fileName)
bool link(const QString &fileName, const QString &linkName)
bool moveToTrash(const QString &fileName, QString *pathInTrash = nullptr)
QFileDevice::Permissions permissions(const QString &fileName)
QFileDevice::Permissions permissions(const std::filesystem::path &filename)
bool remove(const QString &fileName)
bool rename(const QString &oldName, const QString &newName)
bool resize(const QString &fileName, qint64 sz)
bool setPermissions(const QString &fileName, QFileDevice::Permissions permissions)
bool setPermissions(const std::filesystem::path &filename, QFileDevice::Permissions permissionSpec)
QString symLinkTarget(const QString &fileName)

Detailed Description

QFile is an I/O device for reading and writing text and binary files and 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:

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:

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the file is encoded in UTF-8. This can be changed using QTextStream::setEncoding().

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:

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

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

Qt APIs related to I/O use UTF-16 based QStrings to represent file paths. Standard C++ APIs ( <cstdio> or <iostream> ) or platform-specific APIs however often need a 8-bit encoded path. You can use encodeName() and decodeName() to convert between both representations.

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:

File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, 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.

Qt’s understanding of file permissions is limited, which affects especially the QFile::setPermissions() function. On Windows, Qt will set only the legacy read-only flag, and that only when none of the Write* flags are passed. Qt does not manipulate access control lists (ACLs), which makes this function mostly useless for NTFS volumes. It may still be of use for USB sticks that use VFAT file systems. POSIX ACLs are not manipulated, either.

On Android, some limitations apply when dealing with content URIs:

  • Access permissions might be needed by prompting the user through the QFileDialog which implements Android’s native file picker.
  • Aim to follow the Scoped storage guidelines, such as using app specific directories instead of other public external directories. For more information, also see storage best practices.
  • Due to the design of Qt APIs (e.g. QFile), it’s not possible to fully integrate the latter APIs with Android’s MediaStore APIs.

Member Function Documentation

QFile:: QFile ()

Constructs a QFile object.

QFile:: QFile (const QString &name)

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

Note: In versions up to and including Qt 6.8, this constructor is implicit, for backward compatibility. Starting from Qt 6.9 this constructor is unconditionally explicit . Users can force this constructor to be explicit even in earlier versions of Qt by defining the QT_EXPLICIT_QFILE_CONSTRUCTION_FROM_PATH macro before including any Qt header.

[since 6.0] QFile:: QFile (const std::filesystem::path &name)

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

Note: In versions up to and including Qt 6.8, this constructor is implicit, for backward compatibility. Starting from Qt 6.9 this constructor is unconditionally explicit . Users can force this constructor to be explicit even in earlier versions of Qt by defining the QT_EXPLICIT_QFILE_CONSTRUCTION_FROM_PATH macro before including any Qt header.

This function was introduced in Qt 6.0.

[explicit] QFile:: QFile ( QObject *parent)

Constructs a new file object with the given parent.

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

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

[since 6.0] QFile:: QFile (const std::filesystem::path &name, QObject *parent)

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

This function was introduced in Qt 6.0.

[virtual] QFile::

Destroys the file object, closing it if necessary.

bool QFile:: copy (const QString &newName)

Copies the file named fileName() to newName.

This file is closed before it is copied.

If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied.

Returns true if successful; otherwise returns false .

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

Note: On Android, this operation is not yet supported for content scheme URIs.

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

This is an overloaded function.

Copies the file named fileName to newName.

This file is closed before it is copied.

If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied.

Returns true if successful; otherwise returns false .

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

Note: On Android, this operation is not yet supported for content scheme URIs.

[since 6.0] bool QFile:: copy (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

[static] QString QFile:: decodeName (const QByteArray &localFileName)

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

[static] QString QFile:: decodeName (const char *localFileName)

This is an overloaded function.

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

[static] QByteArray QFile:: encodeName (const QString &fileName)

Converts fileName to an 8-bit encoding that you can use in native APIs. On Windows, the encoding is the one from active Windows (ANSI) codepage. On other platforms, this is UTF-8, for macOS in decomposed form (NFD).

[static] bool QFile:: exists (const QString &fileName)

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

Note: If fileName is a symlink that points to a non-existing file, false is returned.

bool QFile:: exists () const

This is an overloaded function.

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

[override virtual] QString QFile:: fileName () const

Returns the name set by setFileName() or to the QFile constructors.

[since 6.0] std::filesystem::path QFile:: filesystemFileName () const

Returns fileName() as std::filesystem::path .

This function was introduced in Qt 6.0.

[since 6.3] std::filesystem::path QFile:: filesystemSymLinkTarget () const

Returns symLinkTarget() as std::filesystem::path .

This function was introduced in Qt 6.3.

[static, since 6.3] std::filesystem::path QFile:: filesystemSymLinkTarget (const std::filesystem::path &fileName)

Returns symLinkTarget() as std::filesystem::path of fileName.

This function was introduced in Qt 6.3.

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 error() to return RenameError.

Note: To create a valid link on Windows, linkName must have a .lnk file extension.

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

This is an overloaded function.

Creates a link named linkName that points to the file 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 .

[since 6.0] bool QFile:: link (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

bool QFile:: moveToTrash ()

Moves the file specified by fileName() to the trash. Returns true if successful, and sets the fileName() to the path at which the file can be found within the trash; otherwise returns false .

Note: On systems where the system API doesn’t report the location of the file in the trash, fileName() will be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.

[static] bool QFile:: moveToTrash (const QString &fileName, QString *pathInTrash = nullptr)

This is an overloaded function.

Moves the file specified by fileName() to the trash. Returns true if successful, and sets pathInTrash (if provided) to the path at which the file can be found within the trash; otherwise returns false .

Note: On systems where the system API doesn’t report the path of the file in the trash, pathInTrash will be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.

[override virtual] bool QFile:: open ( QIODeviceBase::OpenMode mode)

Reimplements: QIODevice::open(QIODeviceBase::OpenMode mode).

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 WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it. The file will be created with mode 0666 masked by the umask on POSIX systems, and with permissions inherited from the parent directory on Windows. On Android, it’s expected to have access permission to the parent of the file name, otherwise, it won’t be possible to create this non-existing file.

[since 6.3] bool QFile:: open ( QIODeviceBase::OpenMode mode, QFileDevice::Permissions permissions)

This is an overloaded function.

If the file does not exist and mode implies creating it, it is created with the specified permissions.

On POSIX systems the actual permissions are influenced by the value of umask .

On Windows the permissions are emulated using ACLs. These ACLs may be in non-canonical order when the group is granted less permissions than others. Files and directories with such permissions will generate warnings when the Security tab of the Properties dialog is opened. Granting the group all permissions granted to others avoids such warnings.

This function was introduced in Qt 6.3.

bool QFile:: open ( FILE *fh, QIODeviceBase::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle)

This is an overloaded function.

Opens the existing file handle fh in the given mode. handleFlags may be used to specify additional options. Returns true if successful; otherwise returns false .

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.

  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 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:

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

This is an overloaded function.

Opens the existing file descriptor fd in the given mode. handleFlags may be used to specify additional options. Returns true if successful; otherwise returns false .

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: 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.

Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.

[override virtual] QFileDevice::Permissions QFile:: permissions () const

[static] QFileDevice::Permissions QFile:: permissions (const QString &fileName)

This is an overloaded function.

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

[static, since 6.0] QFileDevice::Permissions QFile:: permissions (const std::filesystem::path &filename)

This is an overloaded function.

This function was introduced in Qt 6.0.

bool QFile:: remove ()

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

The file is closed before it is removed.

[static] bool QFile:: remove (const QString &fileName)

This is an overloaded function.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false .

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.

If the rename operation fails, Qt will attempt to copy this file’s contents to newName, and then remove this file, keeping only newName. If that copy operation fails or this file can’t be removed, the destination file newName is removed to restore the old state.

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

This is an overloaded function.

Renames the file oldName to newName. Returns true if successful; otherwise returns false .

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

[since 6.0] bool QFile:: rename (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] bool QFile:: resize ( qint64 sz)

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

This is an overloaded function.

Sets fileName to size (in bytes) sz. Returns true 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.

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

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.

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

[since 6.0] void QFile:: setFileName (const std::filesystem::path &name)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] bool QFile:: setPermissions ( QFileDevice::Permissions permissions)

Reimplements: 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.

[static] bool QFile:: setPermissions (const QString &fileName, QFileDevice::Permissions permissions)

This is an overloaded function.

Sets the permissions for fileName file to permissions.

[static, since 6.0] bool QFile:: setPermissions (const std::filesystem::path &filename, QFileDevice::Permissions permissionSpec)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] qint64 QFile:: size () const

[static] QString QFile:: 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.

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.

QString QFile:: symLinkTarget () const

This is an overloaded function.

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.

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.

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

QFile Class Reference
[QtCore module]

Note: All the functions in this class are reentrant, except setEncodingFunction() and setDecodingFunction().

Public Types

Public Functions

Static Public Members

Additional Inherited Members

Detailed Description

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

QFile is an I/O device for reading and writing text and binary files and 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:

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:

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:

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:

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.

Member Type Documentation

typedef QFile::DecoderFn

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

typedef QFile::EncoderFn

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

enum QFile::FileError

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

Constant Value Description
QFile::NoError 0 No error occurred.
QFile::ReadError 1 An error occurred when reading from the file.
QFile::WriteError 2 An error occurred when writing to the file.
QFile::FatalError 3 A fatal error occurred.
QFile::ResourceError 4
QFile::OpenError 5 The file could not be opened.
QFile::AbortError 6 The operation was aborted.
QFile::TimeOutError 7 A timeout occurred.
QFile::UnspecifiedError 8 An unspecified error occurred.
QFile::RemoveError 9 The file could not be removed.
QFile::RenameError 10 The file could not be renamed.
QFile::PositionError 11 The position in the file could not be changed.
QFile::ResizeError 12 The file could not be resized.
QFile::PermissionsError 13 The file could not be accessed.
QFile::CopyError 14 The file could not be copied.

enum QFile::MemoryMapFlags

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

Constant Value Description
QFile::NoOptions 0 No options.

This enum was introduced in Qt 4.4.

enum QFile::Permission
flags QFile::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
QFile::ReadOwner 0x4000 The file is readable by the owner of the file.
QFile::WriteOwner 0x2000 The file is writable by the owner of the file.
QFile::ExeOwner 0x1000 The file is executable by the owner of the file.
QFile::ReadUser 0x0400 The file is readable by the user.
QFile::WriteUser 0x0200 The file is writable by the user.
QFile::ExeUser 0x0100 The file is executable by the user.
QFile::ReadGroup 0x0040 The file is readable by the group.
QFile::WriteGroup 0x0020 The file is writable by the group.
QFile::ExeGroup 0x0010 The file is executable by the group.
QFile::ReadOther 0x0004 The file is readable by anyone.
QFile::WriteOther 0x0002 The file is writable by anyone.
QFile::ExeOther 0x0001 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.

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

typedef QFile::PermissionSpec

Member Function Documentation

QFile::QFile ( const QString & name )

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

QFile::QFile ( QObject * parent )

Constructs a new file object with the given parent.

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

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

QFile::

Destroys the file object, closing it if necessary.

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.

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.

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

This is an overloaded member function, provided for convenience.

Copies the file fileName to newName. 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).

QString QFile::decodeName ( const QByteArray & localFileName ) [static]

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

QString QFile::decodeName ( const char * localFileName ) [static]

This is an overloaded member function, provided for convenience.

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

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.

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.

bool QFile::exists ( const QString & fileName ) [static]

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

bool QFile::exists () const

This is an overloaded member function, provided for convenience.

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

QString QFile::fileName () const

Returns the name set by setFileName() or to the QFile constructors.

bool QFile::flush ()

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

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.

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.

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 error() to return RenameError.

Note: To create a valid link on Windows, linkName must have a .lnk file extension.

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

This is an overloaded member function, provided for convenience.

Creates a link named linkName that points to the file 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.

uchar * QFile::map ( qint64 offset, qint64 size, 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.

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.

This function was introduced in Qt 4.4.

bool QFile::open ( OpenMode mode ) [virtual]

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

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

Note: Because of limitations in the native API, QFile ignores the Unbuffered flag on Windows.

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

This is an overloaded member function, provided for convenience.

Opens the existing file handle fh in the given mode. Returns true if successful; otherwise returns false.

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

  1. If fh is stdin, stdout, or stderr, you may not be able to seek(). See QIODevice::isSequentialAccess() 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 seek() and resize(). Also, size() is set to 0.

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:

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

This is an overloaded member function, provided for convenience.

Opens the existing file descripter fd in the given mode. 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 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). size() is set to LLONG_MAX (in <climits>).

Warning: For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() is set to 0.

Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.

Permissions QFile::permissions () const

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

Permissions QFile::permissions ( const QString & fileName ) [static]

This is an overloaded member function, provided for convenience.

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

bool QFile::remove ()

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

The file is closed before it is removed.

bool QFile::remove ( const QString & fileName ) [static]

This is an overloaded member function, provided for convenience.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false.

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.

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

This is an overloaded member function, provided for convenience.

Renames the file oldName to newName. Returns true if successful; otherwise returns false.

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

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.

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

This is an overloaded member function, provided for convenience.

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

void QFile::setDecodingFunction ( DecoderFn function ) [static]

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

Warning: This function is not reentrant.

void QFile::setEncodingFunction ( EncoderFn function ) [static]

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

Warning: This function is not reentrant.

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.

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

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.

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

This is an overloaded member function, provided for convenience.

Sets the permissions for fileName file to permissions.

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

QString QFile::symLinkTarget ( const QString & fileName ) [static]

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.

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.

This function was introduced in Qt 4.2.

QString QFile::symLinkTarget () const

This is an overloaded member function, provided for convenience.

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.

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.

QFile Class

Примечание. Все функции этого класса реентерабельны .

Public Functions

Реализованные общественные функции

virtual QString имя_файла () переопределить
virtual bool open(QIODeviceBase::OpenMode mode ) override
virtual QFileDevice::Permissions разрешения () переопределить константу
virtual bool resize(qint64 sz ) override
virtual bool setPermissions(QFileDevice::Permissions permissions ) override
virtual qint64 переопределение константы size ()

Статические общественные члены

bool copy(const QString & fileName , const QString & newName )
QString decodeName(const QByteArray & localFileName )
QString decodeName(const char * localFileName )
QByteArray encodeName(const QString & fileName )
bool существует (const QString & fileName )
bool ссылка (const QString & fileName , const QString & linkName )
bool moveToTrash (константа QString и fileName , QString * pathInTrash = nullptr)
QFileDevice::Permissions разрешения (const QString & fileName )
QFileDevice::Permissions разрешения (const std::filesystem::path & filename )
bool удалить (const QString & fileName )
bool переименовать (const QString & oldName , const QString & newName )
bool изменить размер (const QString & fileName , qint64 sz )
bool setPermissions(const QString & fileName , QFileDevice::Permissions permissions )
bool setPermissions(const std::filesystem::path & filename , QFileDevice::Permissions permissionSpec )
QString symLinkTarget (константа QString и fileName )

Detailed Description

QFile — это устройство ввода-вывода для чтения и записи текстовых и двоичных файлов и ресурсов . QFile может использоваться сам по себе или, что более удобно, с QTextStream или QDataStream .

Имя файла обычно передается в конструкторе, но его можно задать в любой момент с помощью setFileName (). QFile ожидает, что разделителем файлов будет ‘/’ независимо от операционной системы. Использование других разделителей (например, ‘\’) не поддерживается.

Вы можете проверить существование файла с помощью exists () и удалить файл с помощью remove (). (Более продвинутые операции, связанные с файловой системой, обеспечивают QFileInfo и QDir .)

Файл открывается с помощью open (), закрывается с помощью close () и очищается с помощью flush (). Данные обычно читаются и записываются с помощью QDataStream или QTextStream , но вы также можете вызывать унаследованные от QIODevice функции read (), readLine (), readAll (), write (). QFile также наследует методы getChar (), putChar () и ungetChar (), которые работают с одним символом за раз.

Размер файла возвращается функцией size (). Вы можете получить текущую позицию в файле с помощью pos () или перейти к новой позиции в файле с помощью seek (). Если вы достигли конца файла, atEnd () возвращает true .

Чтение файлов Непосредственно

В следующем примере строка за строкой читается текстовый файл:

Флаг QIODevice::Text, переданный в open (), указывает Qt преобразовать символы конца строки в стиле Windows («\r\n») в символы конца строки в стиле C++ («\n»). По умолчанию QFile предполагает двоичный формат, т. е. не выполняет никакого преобразования байтов, хранящихся в файле.

Использование потоков для чтения файлов

В следующем примере QTextStream используется для построчного чтения текстового файла:

QTextStream заботится о преобразовании 8-битных данных, хранящихся на диске, в 16-битную Unicode QString . По умолчанию предполагается, что файл закодирован в UTF-8. Это можно изменить с помощью QTextStream::setEncoding ().

Чтобы написать текст, мы можем использовать operator << (), который перегружен, чтобы взять QTextStream слева и различные типы данных (включая QString ) справа:

QDataStream аналогичен тому, что вы можете использовать operator << () для записи данных и operator >> () для их чтения. Подробности смотрите в документации класса.

Когда вы используете QFile, QFileInfo и QDir для доступа к файловой системе с помощью Qt, вы можете использовать имена файлов Unicode. В Unix эти имена файлов преобразуются в 8-битную кодировку. Если вы хотите использовать стандартные API C ++ ( <cstdio> или <iostream> ) или API для конкретных платформ для доступа к файлам вместо QFile, вы можете использовать функции encodeName () и decodeName () для преобразования между именами файлов Unicode и 8- битовые имена файлов.

В Unix есть некоторые специальные системные файлы (например, в /proc ), для которых size () всегда будет возвращать 0, но вы все равно сможете прочитать больше данных из такого файла; данные генерируются в прямом ответе на ваш вызов read (). Однако в этом случае вы не можете использовать atEnd (), чтобы определить, есть ли еще данные для чтения (поскольку atEnd () вернет true для файла, который утверждает, что имеет размер 0). Вместо этого вы должны либо вызывать readAll (), либо вызывать read () или readLine () несколько раз до тех пор, пока не перестанут считываться данные. В следующем примере QTextStream используется для чтения /proc/modules построчно:

Signals

В отличие от других реализаций QIODevice , таких как QTcpSocket , QFile не генерирует сигналы aboutToClose (), bytesWritten () или readyRead (). Эта деталь реализации означает, что QFile не подходит для чтения и записи определенных типов файлов, таких как файлы устройств на платформах Unix.

Конкретные вопросы платформы

Права доступа к файлам обрабатываются по-разному в Unix-подобных системах и Windows. В недоступном для записи каталоге в Unix-подобных системах файлы не могут быть созданы. Это не всегда так в Windows, где, например, каталог «Мои документы» обычно недоступен для записи, но в нем все же можно создавать файлы.

Понимание Qt прав доступа к файлам ограничено, что особенно влияет на функцию QFile::setPermissions (). В Windows Qt установит только устаревший флаг только для чтения и только в том случае, если не передан ни один из флагов Write*. Qt не манипулирует списками управления доступом (ACL), что делает эту функцию практически бесполезной для томов NTFS. Это все еще может быть полезно для USB-накопителей, использующих файловые системы VFAT. Списки контроля доступа POSIX также не изменяются.

Документация по функциям члена

[since 6.0] QFile::QFile(const std::filesystem::path & name , QОбъект * parent )

Создает новый файловый объект с заданным parent представлять файл с указанным name .

Эта функция была введена в Qt 6.0.

QFile::QFile(const QString & name , QОбъект * parent )

Создает новый файловый объект с заданным parent представлять файл с указанным name .

QFile::QFile(QObject * parent )

Создает новый файловый объект с заданным parent .

[since 6.0] QFile::QFile(const std::filesystem::path & name )

Создает новый файловый объект для представления файла с заданным параметром name .

Эта функция была введена в Qt 6.0.

QFile::QFile(const QString & name )

Создает новый файловый объект для представления файла с заданным параметром name .

QFile::QFile()

Конструирует объект QFile.

[virtual] QFile::

Уничтожает файловый объект,закрывая его при необходимости.

bool QFile::copy(const QString & newName )

Копирует файл с именем fileName () в newName .

Этот файл закрывается перед копированием.

Если копируемый файл является символической ссылкой (symlink),копируется файл,на который она ссылается,а не сама ссылка.За исключением разрешений,которые копируются,никакие другие метаданные файла не копируются.

В случае успеха возвращает true ; в противном случае возвращает false .

Обратите внимание,что если файл с именем newName уже существует, функция copy() возвращает false . Это означает , что QFile не перезапишет его.

[since 6.0] bool QFile::copy(const std::filesystem::path & newName )

Это перегруженная функция.

Эта функция была введена в Qt 6.0.

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

Это перегруженная функция.

Копирует файл с именем fileName to newName .

Этот файл закрывается перед копированием.

Если копируемый файл является символической ссылкой (symlink),копируется файл,на который она ссылается,а не сама ссылка.За исключением разрешений,которые копируются,никакие другие метаданные файла не копируются.

В случае успеха возвращает true ; в противном случае возвращает false .

Обратите внимание,что если файл с именем newName уже существует, функция copy() возвращает false . Это означает , что QFile не перезапишет его.

[static] QString QFile::decodeName(const QByteArray & localFileName )

Это делает обратное QFile :: encodeName (), используя localFileName .

[static] QString QFile::decodeName(const char * localFileName )

Это перегруженная функция.

Возвращает версию Юникода данной localFileName . См. Подробности в encodeName ().

[static] QByteArray QFile::encodeName(const QString & fileName )

Converts fileName в локальной 8-битной кодировке,определяемой локалью пользователя.Этого достаточно для имен файлов,которые выбирает пользователь.Имена файлов,жестко закодированные в приложении,должны использовать только 7-битные символы ASCII имён файлов.

[static] bool QFile::exists(const QString & fileName )

Возвращает true если файл, указанный в fileName существуют; в противном случае возвращает false .

Note: If fileName это сим-ссылка,которая указывает на несуществующий файл,возвращается false.

Qt коддинг

Это будет первый из нескольких способов чтения данных из файлов. Я постараюсь постепенно усложнять процесс чтения, но при этом будет повышаться эффективность для конкретных задач.

Создадим стандартное Gui приложение Qt с названием fileReading.
На выходе получим 5 файлов:
fileReading.pro — файл проекта;
mainwindow.h — заголовочный файл главного окна;
mainwindow.cpp — файл исходных кодов главного окна;
main.cpp — main.cpp :);
mainwindow.ui — файл формы главного окна.

Итак, в файле mainwindow.h подключаем QFile для работы с файлами и QDebug дабы выводить считанную информацию в консоль.

Также нам потребуется QByteArray , который нам будет возвращать класс QFile .

Ну и конечно же класс строки, без которого не обходится ни одна GUI программа.

В этом же файле объявим функцию для чтения из файла:

Теперь переходим в mainwindow.cpp. В этом файле определим нашу функцию.

В конструкторе file указывается имя файла, либо полный путь до файла, который необходимо считать, так что предварительно вам будет необходимо его создать.
Надеюсь закомментировал все наглядно.

10 комментариев:

Да, очень хорошо. Спасибо!

мда.. времени, конечно, прошло порядочно, но, может, подскажете?
как реализовать средствами Qt чтение без буфера? нужен аналог вот такого кода:
< FILE *f = fopen(str,"r");
setbuf(f,NULL); >
А Qt, как я понимаю, по-умолчанию буфер включает — как отключить -не могу найти. (

Не совсем понимаю что вы хотите от кода.
Возможно вам поможет QDataStream?

Спасибо, очень помогло. Но к сожалению не читает кирилические символы. Вы знаете как исправить?

Этот комментарий был удален автором.

Не могу прочесть байты

#include [QFile]// все как положено (здесь угловые скобки не позволяют сорри)
#include [QByteArray]// ага.
.
public:
explicit
.
int n;// еще вот эту переменную объявим

QFile file("d:\\file.txt");/* выбрали файл, переменая "file" теперь за все отвечает. да два слеша обязательно!)) */
QByteArray n file.read(1);/* читаем в переменную n по одному байту — (1)*/

и вот далее я не могу эту "n" использовать, пусто. Берет как Hex как Char, но не как Int, даже Byte такого типа не нашел (чтобы n.fromByte();)
__________________________

В общем, сам отыскал =) вдруг кому приргодится

Создаем еще строковую, текстовую переменную (там, в "explicit", mainwindow.h)
QString s;

теперь идем в mainwindow.cpp и пишем

QByteArray str = file.read(1).toHex();/* прочитали байт как Hex-число в строку */
n = str.toInt();/* преобразовали его в байт, в целое число. ну, был байт 13, а в хэксе он 0D и вот она из 0D опять в 13 перевела, жаль, что сразу нельзя 13 получить в Int!*/

теперь n можно анализировать (если обрабатываете бинарный, не текстовый файл), а я искал в файлах байты перевода строки #0D, #0A, которые читая файл как текст не обнаружишь.

Еще остался без ответа пост "Но к сожалению не читает кирилические символы."
Тут есть особенность. Текстовый файл может быть не в режиме cp1251, или там koi-8, а в юникоде, т.е. UTF8. Это значит, что теперь все нац.символы кодируются в два байта. Скажем, раньше за русскую букву "ю" отвечал байт 209, а теперь будут отвечать 209 и 142 и читать их следует парой). Если прочесть по-байтно, то первый символ будет считаться управляющим и в тексте его программа не разместит. Либо выскочит абракадабра, либо вопросики, или вообще ничего. Но тут еще препятствие — BOM.
Надо прочитать начало текстового файла и выяснить наличие этого BOM, оy сообщает, что сейчас символы пойдут парами, хотя есть UTF8 и без bom.
Вообще, чтобы так уж не "запариваться", лучше прочесть все в текстовую переменную (если файл небольшой) иkb выполнить что-то вроде:

QTextStream in(&inFile);// откуда читаем
QTextStream out(&outFile);// куда записываем
out.setCodec("UTF-8");// пишем в юникод

а для текстовых переменных:
string1 = ". кусок текста в кодировке UTF8"
string2 = string1.fromUTF8();// но string2 должна быть cp1251, т.е. не UTF8
/* или */
string2 = QString::fromUtf8(string1);

QFile Class

Note: All functions in this class are reentrant.

Public Functions

Reimplemented Public Functions

virtual QString fileName() const override
virtual bool open(QIODeviceBase::OpenMode mode) override
virtual QFileDevice::Permissions permissions() const override
virtual bool resize(qint64 sz) override
virtual bool setPermissions(QFileDevice::Permissions permissions) override
virtual qint64 size() const override

Static Public Members

bool copy(const QString &fileName, const QString &newName)
QString decodeName(const QByteArray &localFileName)
QString decodeName(const char *localFileName)
QByteArray encodeName(const QString &fileName)
bool exists(const QString &fileName)
std::filesystem::path filesystemSymLinkTarget(const std::filesystem::path &fileName)
bool link(const QString &fileName, const QString &linkName)
bool moveToTrash(const QString &fileName, QString *pathInTrash = nullptr)
QFileDevice::Permissions permissions(const QString &fileName)
QFileDevice::Permissions permissions(const std::filesystem::path &filename)
bool remove(const QString &fileName)
bool rename(const QString &oldName, const QString &newName)
bool resize(const QString &fileName, qint64 sz)
bool setPermissions(const QString &fileName, QFileDevice::Permissions permissions)
bool setPermissions(const std::filesystem::path &filename, QFileDevice::Permissions permissionSpec)
QString symLinkTarget(const QString &fileName)

Detailed Description

QFile is an I/O device for reading and writing text and binary files and 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:

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:

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the file is encoded in UTF-8. This can be changed using QTextStream::setEncoding().

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:

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

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

Qt APIs related to I/O use UTF-16 based QStrings to represent file paths. Standard C++ APIs ( <cstdio> or <iostream> ) or platform-specific APIs however often need a 8-bit encoded path. You can use encodeName() and decodeName() to convert between both representations.

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:

File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, 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.

Qt’s understanding of file permissions is limited, which affects especially the QFile::setPermissions() function. On Windows, Qt will set only the legacy read-only flag, and that only when none of the Write* flags are passed. Qt does not manipulate access control lists (ACLs), which makes this function mostly useless for NTFS volumes. It may still be of use for USB sticks that use VFAT file systems. POSIX ACLs are not manipulated, either.

On Android, some limitations apply when dealing with content URIs:

  • Access permissions might be needed by prompting the user through the QFileDialog which implements Android’s native file picker.
  • Aim to follow the Scoped storage guidelines, such as using app specific directories instead of other public external directories. For more information, also see storage best practices.
  • Due to the design of Qt APIs (e.g. QFile), it’s not possible to fully integrate the latter APIs with Android’s MediaStore APIs.

Member Function Documentation

QFile:: QFile ()

Constructs a QFile object.

QFile:: QFile (const QString &name)

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

Note: In versions up to and including Qt 6.8, this constructor is implicit, for backward compatibility. Starting from Qt 6.9 this constructor is unconditionally explicit . Users can force this constructor to be explicit even in earlier versions of Qt by defining the QT_EXPLICIT_QFILE_CONSTRUCTION_FROM_PATH macro before including any Qt header.

[since 6.0] QFile:: QFile (const std::filesystem::path &name)

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

Note: In versions up to and including Qt 6.8, this constructor is implicit, for backward compatibility. Starting from Qt 6.9 this constructor is unconditionally explicit . Users can force this constructor to be explicit even in earlier versions of Qt by defining the QT_EXPLICIT_QFILE_CONSTRUCTION_FROM_PATH macro before including any Qt header.

This function was introduced in Qt 6.0.

[explicit] QFile:: QFile ( QObject *parent)

Constructs a new file object with the given parent.

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

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

[since 6.0] QFile:: QFile (const std::filesystem::path &name, QObject *parent)

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

This function was introduced in Qt 6.0.

[virtual] QFile::

Destroys the file object, closing it if necessary.

bool QFile:: copy (const QString &newName)

Copies the file named fileName() to newName.

This file is closed before it is copied.

If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied.

Returns true if successful; otherwise returns false .

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

Note: On Android, this operation is not yet supported for content scheme URIs.

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

This is an overloaded function.

Copies the file named fileName to newName.

This file is closed before it is copied.

If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied.

Returns true if successful; otherwise returns false .

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

Note: On Android, this operation is not yet supported for content scheme URIs.

[since 6.0] bool QFile:: copy (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

[static] QString QFile:: decodeName (const QByteArray &localFileName)

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

[static] QString QFile:: decodeName (const char *localFileName)

This is an overloaded function.

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

[static] QByteArray QFile:: encodeName (const QString &fileName)

Converts fileName to an 8-bit encoding that you can use in native APIs. On Windows, the encoding is the one from active Windows (ANSI) codepage. On other platforms, this is UTF-8, for macOS in decomposed form (NFD).

[static] bool QFile:: exists (const QString &fileName)

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

Note: If fileName is a symlink that points to a non-existing file, false is returned.

bool QFile:: exists () const

This is an overloaded function.

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

[override virtual] QString QFile:: fileName () const

Returns the name set by setFileName() or to the QFile constructors.

[since 6.0] std::filesystem::path QFile:: filesystemFileName () const

Returns fileName() as std::filesystem::path .

This function was introduced in Qt 6.0.

[since 6.3] std::filesystem::path QFile:: filesystemSymLinkTarget () const

Returns symLinkTarget() as std::filesystem::path .

This function was introduced in Qt 6.3.

[static, since 6.3] std::filesystem::path QFile:: filesystemSymLinkTarget (const std::filesystem::path &fileName)

Returns symLinkTarget() as std::filesystem::path of fileName.

This function was introduced in Qt 6.3.

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 error() to return RenameError.

Note: To create a valid link on Windows, linkName must have a .lnk file extension.

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

This is an overloaded function.

Creates a link named linkName that points to the file 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 .

[since 6.0] bool QFile:: link (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

bool QFile:: moveToTrash ()

Moves the file specified by fileName() to the trash. Returns true if successful, and sets the fileName() to the path at which the file can be found within the trash; otherwise returns false .

Note: On systems where the system API doesn’t report the location of the file in the trash, fileName() will be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.

[static] bool QFile:: moveToTrash (const QString &fileName, QString *pathInTrash = nullptr)

This is an overloaded function.

Moves the file specified by fileName() to the trash. Returns true if successful, and sets pathInTrash (if provided) to the path at which the file can be found within the trash; otherwise returns false .

Note: On systems where the system API doesn’t report the path of the file in the trash, pathInTrash will be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.

[override virtual] bool QFile:: open ( QIODeviceBase::OpenMode mode)

Reimplements: QIODevice::open(QIODeviceBase::OpenMode mode).

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 WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it. The file will be created with mode 0666 masked by the umask on POSIX systems, and with permissions inherited from the parent directory on Windows. On Android, it’s expected to have access permission to the parent of the file name, otherwise, it won’t be possible to create this non-existing file.

[since 6.3] bool QFile:: open ( QIODeviceBase::OpenMode mode, QFileDevice::Permissions permissions)

This is an overloaded function.

If the file does not exist and mode implies creating it, it is created with the specified permissions.

On POSIX systems the actual permissions are influenced by the value of umask .

On Windows the permissions are emulated using ACLs. These ACLs may be in non-canonical order when the group is granted less permissions than others. Files and directories with such permissions will generate warnings when the Security tab of the Properties dialog is opened. Granting the group all permissions granted to others avoids such warnings.

This function was introduced in Qt 6.3.

bool QFile:: open ( FILE *fh, QIODeviceBase::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle)

This is an overloaded function.

Opens the existing file handle fh in the given mode. handleFlags may be used to specify additional options. Returns true if successful; otherwise returns false .

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.

  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 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:

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

This is an overloaded function.

Opens the existing file descriptor fd in the given mode. handleFlags may be used to specify additional options. Returns true if successful; otherwise returns false .

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: 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.

Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.

[override virtual] QFileDevice::Permissions QFile:: permissions () const

[static] QFileDevice::Permissions QFile:: permissions (const QString &fileName)

This is an overloaded function.

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

[static, since 6.0] QFileDevice::Permissions QFile:: permissions (const std::filesystem::path &filename)

This is an overloaded function.

This function was introduced in Qt 6.0.

bool QFile:: remove ()

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

The file is closed before it is removed.

[static] bool QFile:: remove (const QString &fileName)

This is an overloaded function.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false .

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.

If the rename operation fails, Qt will attempt to copy this file’s contents to newName, and then remove this file, keeping only newName. If that copy operation fails or this file can’t be removed, the destination file newName is removed to restore the old state.

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

This is an overloaded function.

Renames the file oldName to newName. Returns true if successful; otherwise returns false .

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

[since 6.0] bool QFile:: rename (const std::filesystem::path &newName)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] bool QFile:: resize ( qint64 sz)

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

This is an overloaded function.

Sets fileName to size (in bytes) sz. Returns true 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.

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

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.

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

[since 6.0] void QFile:: setFileName (const std::filesystem::path &name)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] bool QFile:: setPermissions ( QFileDevice::Permissions permissions)

Reimplements: 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.

[static] bool QFile:: setPermissions (const QString &fileName, QFileDevice::Permissions permissions)

This is an overloaded function.

Sets the permissions for fileName file to permissions.

[static, since 6.0] bool QFile:: setPermissions (const std::filesystem::path &filename, QFileDevice::Permissions permissionSpec)

This is an overloaded function.

This function was introduced in Qt 6.0.

[override virtual] qint64 QFile:: size () const

[static] QString QFile:: 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.

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.

QString QFile:: symLinkTarget () const

This is an overloaded function.

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.

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.

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

QFile Class Reference
[QtCore module]

Note: All the functions in this class are reentrant, except setEncodingFunction() and setDecodingFunction().

Public Types

Public Functions

Static Public Members

Additional Inherited Members

Detailed Description

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

QFile is an I/O device for reading and writing text and binary files and 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:

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:

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:

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:

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.

Member Type Documentation

typedef QFile::DecoderFn

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

typedef QFile::EncoderFn

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

enum QFile::FileError

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

Constant Value Description
QFile::NoError 0 No error occurred.
QFile::ReadError 1 An error occurred when reading from the file.
QFile::WriteError 2 An error occurred when writing to the file.
QFile::FatalError 3 A fatal error occurred.
QFile::ResourceError 4
QFile::OpenError 5 The file could not be opened.
QFile::AbortError 6 The operation was aborted.
QFile::TimeOutError 7 A timeout occurred.
QFile::UnspecifiedError 8 An unspecified error occurred.
QFile::RemoveError 9 The file could not be removed.
QFile::RenameError 10 The file could not be renamed.
QFile::PositionError 11 The position in the file could not be changed.
QFile::ResizeError 12 The file could not be resized.
QFile::PermissionsError 13 The file could not be accessed.
QFile::CopyError 14 The file could not be copied.

enum QFile::MemoryMapFlags

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

Constant Value Description
QFile::NoOptions 0 No options.

This enum was introduced in Qt 4.4.

enum QFile::Permission
flags QFile::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
QFile::ReadOwner 0x4000 The file is readable by the owner of the file.
QFile::WriteOwner 0x2000 The file is writable by the owner of the file.
QFile::ExeOwner 0x1000 The file is executable by the owner of the file.
QFile::ReadUser 0x0400 The file is readable by the user.
QFile::WriteUser 0x0200 The file is writable by the user.
QFile::ExeUser 0x0100 The file is executable by the user.
QFile::ReadGroup 0x0040 The file is readable by the group.
QFile::WriteGroup 0x0020 The file is writable by the group.
QFile::ExeGroup 0x0010 The file is executable by the group.
QFile::ReadOther 0x0004 The file is readable by anyone.
QFile::WriteOther 0x0002 The file is writable by anyone.
QFile::ExeOther 0x0001 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.

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

typedef QFile::PermissionSpec

Member Function Documentation

QFile::QFile ( const QString & name )

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

QFile::QFile ( QObject * parent )

Constructs a new file object with the given parent.

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

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

QFile::

Destroys the file object, closing it if necessary.

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.

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.

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

This is an overloaded member function, provided for convenience.

Copies the file fileName to newName. 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).

QString QFile::decodeName ( const QByteArray & localFileName ) [static]

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

QString QFile::decodeName ( const char * localFileName ) [static]

This is an overloaded member function, provided for convenience.

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

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.

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.

bool QFile::exists ( const QString & fileName ) [static]

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

bool QFile::exists () const

This is an overloaded member function, provided for convenience.

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

QString QFile::fileName () const

Returns the name set by setFileName() or to the QFile constructors.

bool QFile::flush ()

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

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.

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.

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 error() to return RenameError.

Note: To create a valid link on Windows, linkName must have a .lnk file extension.

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

This is an overloaded member function, provided for convenience.

Creates a link named linkName that points to the file 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.

uchar * QFile::map ( qint64 offset, qint64 size, 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.

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.

This function was introduced in Qt 4.4.

bool QFile::open ( OpenMode mode ) [virtual]

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

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

Note: Because of limitations in the native API, QFile ignores the Unbuffered flag on Windows.

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

This is an overloaded member function, provided for convenience.

Opens the existing file handle fh in the given mode. Returns true if successful; otherwise returns false.

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

  1. If fh is stdin, stdout, or stderr, you may not be able to seek(). See QIODevice::isSequentialAccess() 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 seek() and resize(). Also, size() is set to 0.

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:

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

This is an overloaded member function, provided for convenience.

Opens the existing file descripter fd in the given mode. 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 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). size() is set to LLONG_MAX (in <climits>).

Warning: For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() is set to 0.

Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.

Permissions QFile::permissions () const

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

Permissions QFile::permissions ( const QString & fileName ) [static]

This is an overloaded member function, provided for convenience.

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

bool QFile::remove ()

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

The file is closed before it is removed.

bool QFile::remove ( const QString & fileName ) [static]

This is an overloaded member function, provided for convenience.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false.

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.

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

This is an overloaded member function, provided for convenience.

Renames the file oldName to newName. Returns true if successful; otherwise returns false.

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

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.

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

This is an overloaded member function, provided for convenience.

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

void QFile::setDecodingFunction ( DecoderFn function ) [static]

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

Warning: This function is not reentrant.

void QFile::setEncodingFunction ( EncoderFn function ) [static]

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

Warning: This function is not reentrant.

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.

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

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.

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

This is an overloaded member function, provided for convenience.

Sets the permissions for fileName file to permissions.

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

QString QFile::symLinkTarget ( const QString & fileName ) [static]

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.

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.

This function was introduced in Qt 4.2.

QString QFile::symLinkTarget () const

This is an overloaded member function, provided for convenience.

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.

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.

Работа с текстовыми файлами в Qt

В библиотеке Qt работа с файлами вообще и текстовыми в частности реализована с помощью класса QFile.

В качестве параметра при создании объекта этого класса передаётся путь к нужному файлу.

После того как объект QFile создан, необходимо открыть файл с помощью метода open. Это метод принимает в качестве параметра режим открытия файла.

Запись в текстовый файл

После открытия текстового файла в режиме записи в него можно записать нужные данные при помощи метода write. После окончания записи файл необходимо обязательно закрыть при помощи метода close.

В данном примере, в случае успешного открытия файла в режиме записи в него будут записаны две строки. Если записываемый файл не существует, он будет создан. В противном случае он будет перезаписан.

Важно отметить, что метод write самостоятельно не добавляет разрыв строки и потому эта задача ложится на плечи программиста.

Чтение из текстового файла

Перед тем как приступить к чтению файла, его необходимо открыть в соответствующем режиме с помощью метода open. Также перед открытием файла для чтения необходимо убедиться в его существовании. Это можно сделать при помощи метода exists ( если файл существует, он возвращает true).

Для построчного чтения из текстового файла у класса QFile предусмотрен специальный метод readLine. Этот метод считывает из файла строку в начале которой в данный момент находится указатель и перемещает его в начало следующей строки.

Чтобы при чтении по ошибке позиция указателя не оказалась «за пределами» файла необходимо проверять является ли позиция указателя концом файла. Для этого служит метод atEnd, который возвратит true, когда конец файла будет достигнут. В противном случае он возвратит false.

После чтения данных из файла его также следует закрыть с помощью метода close.

QFile Class

Примечание. Все функции этого класса реентерабельны .

Public Functions

Реализованные общественные функции

virtual QString имя_файла () переопределить
virtual bool open(QIODeviceBase::OpenMode mode ) override
virtual QFileDevice::Permissions разрешения () переопределить константу
virtual bool resize(qint64 sz ) override
virtual bool setPermissions(QFileDevice::Permissions permissions ) override
virtual qint64 переопределение константы size ()

Статические общественные члены

bool copy(const QString & fileName , const QString & newName )
QString decodeName(const QByteArray & localFileName )
QString decodeName(const char * localFileName )
QByteArray encodeName(const QString & fileName )
bool существует (const QString & fileName )
bool ссылка (const QString & fileName , const QString & linkName )
bool moveToTrash (константа QString и fileName , QString * pathInTrash = nullptr)
QFileDevice::Permissions разрешения (const QString & fileName )
QFileDevice::Permissions разрешения (const std::filesystem::path & filename )
bool удалить (const QString & fileName )
bool переименовать (const QString & oldName , const QString & newName )
bool изменить размер (const QString & fileName , qint64 sz )
bool setPermissions(const QString & fileName , QFileDevice::Permissions permissions )
bool setPermissions(const std::filesystem::path & filename , QFileDevice::Permissions permissionSpec )
QString symLinkTarget (константа QString и fileName )

Detailed Description

QFile — это устройство ввода-вывода для чтения и записи текстовых и двоичных файлов и ресурсов . QFile может использоваться сам по себе или, что более удобно, с QTextStream или QDataStream .

Имя файла обычно передается в конструкторе, но его можно задать в любой момент с помощью setFileName (). QFile ожидает, что разделителем файлов будет ‘/’ независимо от операционной системы. Использование других разделителей (например, ‘\’) не поддерживается.

Вы можете проверить существование файла с помощью exists () и удалить файл с помощью remove (). (Более продвинутые операции, связанные с файловой системой, обеспечивают QFileInfo и QDir .)

Файл открывается с помощью open (), закрывается с помощью close () и очищается с помощью flush (). Данные обычно читаются и записываются с помощью QDataStream или QTextStream , но вы также можете вызывать унаследованные от QIODevice функции read (), readLine (), readAll (), write (). QFile также наследует методы getChar (), putChar () и ungetChar (), которые работают с одним символом за раз.

Размер файла возвращается функцией size (). Вы можете получить текущую позицию в файле с помощью pos () или перейти к новой позиции в файле с помощью seek (). Если вы достигли конца файла, atEnd () возвращает true .

Чтение файлов Непосредственно

В следующем примере строка за строкой читается текстовый файл:

Флаг QIODevice::Text, переданный в open (), указывает Qt преобразовать символы конца строки в стиле Windows («\r\n») в символы конца строки в стиле C++ («\n»). По умолчанию QFile предполагает двоичный формат, т. е. не выполняет никакого преобразования байтов, хранящихся в файле.

Использование потоков для чтения файлов

В следующем примере QTextStream используется для построчного чтения текстового файла:

QTextStream заботится о преобразовании 8-битных данных, хранящихся на диске, в 16-битную Unicode QString . По умолчанию предполагается, что файл закодирован в UTF-8. Это можно изменить с помощью QTextStream::setEncoding ().

Чтобы написать текст, мы можем использовать operator << (), который перегружен, чтобы взять QTextStream слева и различные типы данных (включая QString ) справа:

QDataStream аналогичен тому, что вы можете использовать operator << () для записи данных и operator >> () для их чтения. Подробности смотрите в документации класса.

Когда вы используете QFile, QFileInfo и QDir для доступа к файловой системе с помощью Qt, вы можете использовать имена файлов Unicode. В Unix эти имена файлов преобразуются в 8-битную кодировку. Если вы хотите использовать стандартные API C ++ ( <cstdio> или <iostream> ) или API для конкретных платформ для доступа к файлам вместо QFile, вы можете использовать функции encodeName () и decodeName () для преобразования между именами файлов Unicode и 8- битовые имена файлов.

В Unix есть некоторые специальные системные файлы (например, в /proc ), для которых size () всегда будет возвращать 0, но вы все равно сможете прочитать больше данных из такого файла; данные генерируются в прямом ответе на ваш вызов read (). Однако в этом случае вы не можете использовать atEnd (), чтобы определить, есть ли еще данные для чтения (поскольку atEnd () вернет true для файла, который утверждает, что имеет размер 0). Вместо этого вы должны либо вызывать readAll (), либо вызывать read () или readLine () несколько раз до тех пор, пока не перестанут считываться данные. В следующем примере QTextStream используется для чтения /proc/modules построчно:

Signals

В отличие от других реализаций QIODevice , таких как QTcpSocket , QFile не генерирует сигналы aboutToClose (), bytesWritten () или readyRead (). Эта деталь реализации означает, что QFile не подходит для чтения и записи определенных типов файлов, таких как файлы устройств на платформах Unix.

Конкретные вопросы платформы

Права доступа к файлам обрабатываются по-разному в Unix-подобных системах и Windows. В недоступном для записи каталоге в Unix-подобных системах файлы не могут быть созданы. Это не всегда так в Windows, где, например, каталог «Мои документы» обычно недоступен для записи, но в нем все же можно создавать файлы.

Понимание Qt прав доступа к файлам ограничено, что особенно влияет на функцию QFile::setPermissions (). В Windows Qt установит только устаревший флаг только для чтения и только в том случае, если не передан ни один из флагов Write*. Qt не манипулирует списками управления доступом (ACL), что делает эту функцию практически бесполезной для томов NTFS. Это все еще может быть полезно для USB-накопителей, использующих файловые системы VFAT. Списки контроля доступа POSIX также не изменяются.

Документация по функциям члена

[since 6.0] QFile::QFile(const std::filesystem::path & name , QОбъект * parent )

Создает новый файловый объект с заданным parent представлять файл с указанным name .

Эта функция была введена в Qt 6.0.

QFile::QFile(const QString & name , QОбъект * parent )

Создает новый файловый объект с заданным parent представлять файл с указанным name .

QFile::QFile(QObject * parent )

Создает новый файловый объект с заданным parent .

[since 6.0] QFile::QFile(const std::filesystem::path & name )

Создает новый файловый объект для представления файла с заданным параметром name .

Эта функция была введена в Qt 6.0.

QFile::QFile(const QString & name )

Создает новый файловый объект для представления файла с заданным параметром name .

QFile::QFile()

Конструирует объект QFile.

[virtual] QFile::

Уничтожает файловый объект,закрывая его при необходимости.

bool QFile::copy(const QString & newName )

Копирует файл с именем fileName () в newName .

Этот файл закрывается перед копированием.

Если копируемый файл является символической ссылкой (symlink),копируется файл,на который она ссылается,а не сама ссылка.За исключением разрешений,которые копируются,никакие другие метаданные файла не копируются.

В случае успеха возвращает true ; в противном случае возвращает false .

Обратите внимание,что если файл с именем newName уже существует, функция copy() возвращает false . Это означает , что QFile не перезапишет его.

[since 6.0] bool QFile::copy(const std::filesystem::path & newName )

Это перегруженная функция.

Эта функция была введена в Qt 6.0.

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

Это перегруженная функция.

Копирует файл с именем fileName to newName .

Этот файл закрывается перед копированием.

Если копируемый файл является символической ссылкой (symlink),копируется файл,на который она ссылается,а не сама ссылка.За исключением разрешений,которые копируются,никакие другие метаданные файла не копируются.

В случае успеха возвращает true ; в противном случае возвращает false .

Обратите внимание,что если файл с именем newName уже существует, функция copy() возвращает false . Это означает , что QFile не перезапишет его.

[static] QString QFile::decodeName(const QByteArray & localFileName )

Это делает обратное QFile :: encodeName (), используя localFileName .

[static] QString QFile::decodeName(const char * localFileName )

Это перегруженная функция.

Возвращает версию Юникода данной localFileName . См. Подробности в encodeName ().

[static] QByteArray QFile::encodeName(const QString & fileName )

Converts fileName в локальной 8-битной кодировке,определяемой локалью пользователя.Этого достаточно для имен файлов,которые выбирает пользователь.Имена файлов,жестко закодированные в приложении,должны использовать только 7-битные символы ASCII имён файлов.

[static] bool QFile::exists(const QString & fileName )

Возвращает true если файл, указанный в fileName существуют; в противном случае возвращает false .

Note: If fileName это сим-ссылка,которая указывает на несуществующий файл,возвращается false.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *