QFile 类提供用于读写文件的接口。 更多...
头: | #include <QFile> |
CMake: |
find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
继承: | QFileDevice |
继承者: | QTemporaryFile |
注意: 此类的所有函数 可重入 .
QFile (const std::filesystem::path & name , QObject * parent ) | |
QFile (const QString & name , QObject * parent ) | |
QFile (QObject * parent ) | |
QFile (const std::filesystem::path & name ) | |
QFile (const QString & name ) | |
QFile () | |
virtual | ~QFile () |
bool | copy (const QString & newName ) |
bool | copy (const std::filesystem::path & newName ) |
bool | exists () const |
std::filesystem::path | filesystemFileName () const |
bool | link (const QString & linkName ) |
bool | link (const std::filesystem::path & newName ) |
bool | moveToTrash () |
bool | open (FILE * fh , QIODeviceBase::OpenMode mode , QFileDevice::FileHandleFlags handleFlags = DontCloseHandle) |
bool | open (int fd , QIODeviceBase::OpenMode mode , QFileDevice::FileHandleFlags handleFlags = DontCloseHandle) |
bool | remove () |
bool | rename (const QString & newName ) |
bool | rename (const std::filesystem::path & newName ) |
void | setFileName (const QString & name ) |
void | setFileName (const std::filesystem::path & name ) |
QString | symLinkTarget () const |
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 |
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 ) |
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 ) |
QFile 是 I/O 设备用于读取和写入文本、二进制文件及 resources 。QFile 可以单独使用,或更方便一起使用与 QTextStream or QDataStream .
通常在构造函数中传递文件名,但可以随时设置它使用 setFileName (). QFile 期望文件分隔符为 / 不管操作系统。不支持使用其它分隔符 (如:\)。
可以检查文件是否存在使用 exists (),和移除文件使用 remove ()。(更高级的文件系统相关操作的提供由 QFileInfo and QDir .)
打开文件采用 open (),关闭采用 close (),和刷新采用 flush ()。数据的读取和写入通常是使用 QDataStream or QTextStream ,但也可以调用 QIODevice -inherited functions read (), readLine (), readAll (), write (). QFile also inherits getChar (), putChar (),和 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
() 返回
true
.
以下范例逐行读取文本文件:
QFile file("in.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; while (!file.atEnd()) { QByteArray line = file.readLine(); process_line(line); }
The QIODevice::Text flag passed to open () 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.
The next example uses QTextStream to read a text file line by line:
QFile file("in.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); process_line(line); }
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:
QFile file("out.txt"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream out(&file); out << "The magic number is: " << 49 << "\n";
QDataStream is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.
When you use QFile,
QFileInfo
,和
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
() 和
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
() 或
readLine
() repeatedly until no more data can be read. The next example uses
QTextStream
to read
/proc/modules
line by line:
QFile file("/proc/modules"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); QString line = in.readLine(); while (!line.isNull()) { process_line(line); line = in.readLine(); }
不像其它 QIODevice 实现,譬如 QTcpSocket ,QFile 不会发射 aboutToClose (), bytesWritten (),或 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.
文件权限的处理是不同的,在像 Unix 系统和 Windows。在非 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 对文件权限的理解是有限的,这尤其影响 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.
另请参阅 QTextStream , QDataStream , QFileInfo , QDir ,和 Qt 资源系统 .
[since 6.0]
QFile::
QFile
(const
std::filesystem::path
&
name
,
QObject
*
parent
)
构造新文件对象采用给定 parent to represent the file with the specified name .
该函数在 Qt 6.0 引入。
构造新文件对象采用给定 parent to represent the file with the specified name .
构造新文件对象采用给定 parent .
[since 6.0]
QFile::
QFile
(const
std::filesystem::path
&
name
)
构造新文件对象以表示文件采用给定 name .
该函数在 Qt 6.0 引入。
构造新文件对象以表示文件采用给定 name .
构造 QFile 对象。
[virtual]
QFile::
~QFile
()
销毁文件对象,关闭它若有必要。
Copies the file named fileName () 到 newName .
此文件被关闭,在拷贝它之前。
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.
返回
true
若成功;否则返回
false
.
注意:若文件采用名称
newName
已存在,copy() 返回
false
. This means
QFile
will not overwrite it.
另请参阅 setFileName ().
[since 6.0]
bool
QFile::
copy
(const
std::filesystem::path
&
newName
)
这是重载函数。
该函数在 Qt 6.0 引入。
[static]
bool
QFile::
copy
(const
QString
&
fileName
, const
QString
&
newName
)
这是重载函数。
Copies the file named fileName to newName .
此文件被关闭,在拷贝它之前。
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.
返回
true
若成功;否则返回
false
.
注意:若文件采用名称
newName
已存在,copy() 返回
false
. This means
QFile
will not overwrite it.
另请参阅 rename ().
[static]
QString
QFile::
decodeName
(const
QByteArray
&
localFileName
)
这做反向 QFile::encodeName () 使用 localFileName .
另请参阅 encodeName ().
[static]
QString
QFile::
decodeName
(const
char
*
localFileName
)
这是重载函数。
返回 Unicode 版本为给定 localFileName 。见 encodeName () 了解细节。
[static]
QByteArray
QFile::
encodeName
(const
QString
&
fileName
)
转换 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.
另请参阅 decodeName ().
[static]
bool
QFile::
exists
(const
QString
&
fileName
)
返回
true
若文件指定通过
fileName
存在;否则返回
false
.
注意: 若 fileName 是指向不存在文件的符号链接,返回 false。
这是重载函数。
返回
true
若文件指定通过
fileName
() 存在;否则返回
false
.
另请参阅 fileName () 和 setFileName ().
[override virtual]
QString
QFile::
fileName
() const
重实现: QFileDevice::fileName () const.
返回名称设置通过 setFileName () 或到 QFile 构造函数。
另请参阅 setFileName () 和 QFileInfo::fileName ().
[since 6.0]
std::filesystem::path
QFile::
filesystemFileName
() const
返回
fileName
() 作为
std::filesystem::path
.
该函数在 Qt 6.0 引入。
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
若成功;否则返回
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
.
注意:
To create a valid link on Windows,
linkName
must have a
.lnk
file extension.
另请参阅 setFileName ().
[since 6.0]
bool
QFile::
link
(const
std::filesystem::path
&
newName
)
这是重载函数。
该函数在 Qt 6.0 引入。
[static]
bool
QFile::
link
(const
QString
&
fileName
, const
QString
&
linkName
)
这是重载函数。
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
若成功;否则返回
false
.
另请参阅 link ().
[since 5.15]
bool
QFile::
moveToTrash
()
移动指定文件按
fileName
() 到垃圾桶。返回
true
若成功,并设置
fileName
() to the path at which the file can be found within the trash; otherwise returns
false
.
注意: 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.
该函数在 Qt 5.15 引入。
[static, since 5.15]
bool
QFile::
moveToTrash
(const
QString
&
fileName
,
QString
*
pathInTrash
= nullptr)
这是重载函数。
移动指定文件按
fileName
() 到垃圾桶。返回
true
if successful, and sets
pathInTrash
(if provided) to the path at which the file can be found within the trash; otherwise returns
false
.
注意: 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.
该函数在 Qt 5.15 引入。
[override virtual]
bool
QFile::
open
(
QIODeviceBase::OpenMode
mode
)
重实现: QIODevice::open (QIODeviceBase::OpenMode mode).
打开文件使用 OpenMode mode ,返回 true,若成功;否则返回 false。
mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.
注意: 在 WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.
另请参阅 QIODevice::OpenMode and setFileName ().
这是重载函数。
打开现有文件句柄
fh
以给定
mode
.
handleFlags
可以用于指定额外选项。返回
true
若成功;否则返回
false
.
范例:
#include <stdio.h> void printError(const char* msg) { QFile file; file.open(stderr, QIODevice::WriteOnly); file.write(msg, qstrlen(msg)); // write to stderr file.close(); }
当 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.
警告:
stdin
,
stdout
,或
stderr
, you may not be able to
seek
().
size
() 返回
0
in those cases. See
QIODevice::isSequential
() 了解更多信息。
Note for the Windows Platform
fh must be opened in binary mode (i.e., the mode string must contain 'b', as in "rb" or "wb") when accessing files and other random-access devices. Qt will translate the end-of-line characters if you pass QIODevice::Text to mode . Sequential devices, such as stdin and stdout, are unaffected by this limitation.
You need to enable support for console applications in order to use the stdin, stdout and stderr streams at the console. To do this, add the following declaration to your application's project file:
CONFIG += console
另请参阅 close ().
这是重载函数。
打开现有文件描述符
fd
以给定
mode
.
handleFlags
可以用于指定额外选项。返回
true
若成功;否则返回
false
.
当 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.
警告:
若
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
() 返回
0
。见
QIODevice::isSequential
() 了解更多信息。
警告: Since this function opens the file without specifying the file name, you cannot use this QFile 采用 QFileInfo .
另请参阅 close ().
[override virtual]
QFileDevice::Permissions
QFile::
permissions
() const
重实现: QFileDevice::permissions () const.
另请参阅 setPermissions ().
[static]
QFileDevice::Permissions
QFile::
permissions
(const
QString
&
fileName
)
这是重载函数。
返回完整 OR 组合在一起的 QFile::Permission 为 fileName .
[static, since 6.0]
QFileDevice::Permissions
QFile::
permissions
(const
std::filesystem::path
&
filename
)
这是重载函数。
该函数在 Qt 6.0 引入。
移除文件指定通过
fileName
()。返回
true
若成功;否则返回
false
.
文件被关闭,在移除它之前。
另请参阅 setFileName ().
[static]
bool
QFile::
remove
(const
QString
&
fileName
)
这是重载函数。
移除文件指定通过 fileName 给定。
返回
true
若成功;否则返回
false
.
另请参阅 remove ().
重命名文件目前指定通过
fileName
() 到
newName
。返回
true
若成功;否则返回
false
.
若文件采用名称
newName
已存在,rename() 返回
false
(即,
QFile
不会覆写它)。
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.
另请参阅 setFileName ().
[since 6.0]
bool
QFile::
rename
(const
std::filesystem::path
&
newName
)
这是重载函数。
该函数在 Qt 6.0 引入。
[static]
bool
QFile::
rename
(const
QString
&
oldName
, const
QString
&
newName
)
这是重载函数。
重命名文件
oldName
to
newName
。返回
true
若成功;否则返回
false
.
若文件采用名称
newName
已存在,rename() 返回
false
(即,
QFile
不会覆写它)。
另请参阅 rename ().
[override virtual]
bool
QFile::
resize
(
qint64
sz
)
重实现: QFileDevice::resize (qint64 sz).
[static]
bool
QFile::
resize
(const
QString
&
fileName
,
qint64
sz
)
这是重载函数。
设置
fileName
to size (in bytes)
sz
。返回
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.
警告: 此函数可能失败,若文件不存在。
另请参阅 resize ().
设置 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 () 调用。
范例:
QFile file; QDir::setCurrent("/tmp"); file.setFileName("readme.txt"); QDir::setCurrent("/home"); file.open(QIODevice::ReadOnly); // opens "/home/readme.txt" under Unix
Note that the directory separator "/" works for all operating systems supported by Qt.
另请参阅 fileName (), QFileInfo ,和 QDir .
[since 6.0]
void
QFile::
setFileName
(const
std::filesystem::path
&
name
)
这是重载函数。
该函数在 Qt 6.0 引入。
[override virtual]
bool
QFile::
setPermissions
(
QFileDevice::Permissions
permissions
)
重实现: QFileDevice::setPermissions (QFileDevice::Permissions permissions).
将文件权限设为
permissions
指定。返回
true
若成功,或
false
若权限不能被修改。
警告: 此函数不操纵 ACL (访问控制列表),这可能限制其有效性。
另请参阅 permissions () 和 setFileName ().
[static]
bool
QFile::
setPermissions
(const
QString
&
fileName
,
QFileDevice::Permissions
permissions
)
这是重载函数。
设置权限为 fileName file to permissions .
[static, since 6.0]
bool
QFile::
setPermissions
(const
std::filesystem::path
&
filename
,
QFileDevice::Permissions
permissionSpec
)
这是重载函数。
该函数在 Qt 6.0 引入。
[override virtual]
qint64
QFile::
size
() const
重实现: QFileDevice::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
() 返回
true
if the symlink points to an existing file.
这是重载函数。
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
() 返回
true
if the symlink points to an existing file.
另请参阅 fileName () 和 setFileName ().