QFile Class

The QFile 提供读写文件的接口. 更多...

头文件: #include <QFile>
qmake: QT += core
基类: QFileDevice
派生类:

QTemporaryFile

Note: All functions in this class are reentrant.

公有类型

typedef DecoderFn

公有函数

QFile()
QFile(const QString &name)
QFile(QObject *parent)
QFile(const QString &name, QObject *parent)
~QFile()
bool copy(const QString &newName)
bool exists() const
bool link(const QString &linkName)
bool open(FILE *fh, OpenMode mode, FileHandleFlags handleFlags = DontCloseHandle)
bool open(int fd, OpenMode mode, FileHandleFlags handleFlags = DontCloseHandle)
bool remove()
bool rename(const QString &newName)
void setFileName(const QString &name)
QString symLinkTarget() const

重新实现的公有函数

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

静态公有成员

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)
Permissions permissions(const QString &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, Permissions permissions)
QString symLinkTarget(const QString &fileName)
  • 11 个静态公有成员继承自 QObject

其他继承的成员

详细描述

QFile 提供读写文件的接口.

QFile 是用于读写文本及二进制的文件及 资源 的 I/O 设备. 一个 QFile 可以单独使用, 或者更简单的, 可以与 QTextStreamQDataStream 一起使用.

文件名通常在构造时传递, 但也可以在随时调用 setFileName() 设置. QFile 需要目录分隔符为 '/', 而不是依照操作系统. 其他分隔符 (如., '\') 不受支持.

你可以调用 exists() 判断文件是否存在, 调用 remove() 移除文件. (更多操作系统相关的操作在 QFileInfoQDir 提供.)

调用 open() 打开, 调用 close() 关闭, 调用 flush() 刷新. 读写数据通常使用 QDataStreamQTextStream, 但是你也可以使用继承自 QIODevice 的函数 read(), readLine(), readAll(), write(). QFile 也继承了函数 getChar(), putChar(), ungetChar(), 你可以使用它们进行单字符操作.

调用 size() 返回文件大小. 你可以调用 pos() 获取当前文件位置, 调用 seek() 移动新位置. 若你读取文件到达结尾, 则调用 atEnd() 返回 true.

直接读取文件

如下例子逐行地直接读取文本文件:


      QFile file("in.txt");
      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
          return;

      while (!file.atEnd()) {
          QByteArray line = file.readLine();
          process_line(line);
      }

QIODevice::Text 作为参数传递给 open() , 目的是告诉 Qt 将 Windows风格的换行符 ("\r\n") 转换为 C++风格 ("\n"). 默认情况下, QFile 假设以二进制模式读取, 即. 对于文件存储的字节不做转换.

使用流读取文件

如下例子使用 QTextStream 逐行读取文本文件:


      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 会特意把8位文件中字节数据转换为 QString 中16位 UTF-16 字符. 默认情况下, 它假设用户使用系统默认编码 (如., unix平台上是 UTF-8; 详见 QTextCodec::codecForLocale()). 改变编码方式可以调用 QTextStream::setCodec().

要写入文本, 你可以使用 operator<<(), 在 QTextStream 中,其重载用于将右侧内容 (QString) 追加的左侧, 示例如下:


      QFile file("out.txt");
      if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
          return;

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

QDataStream 类似, 你可以使用 operator<<() 写数据, 使用 operator>>() 读数据. 详见 QDataStream 文档.

当使用 QFile, QFileInfo, QDir 访问系统文件时, 你可以使用 Unicode 文件名. 在 Unix 上, 文件名转化为 8 位编码方式. 如果你想使用 C++ 标准 API (<cstdio><iostream>) 或平台相关 API, 而不使用 QFile, 你可以调用 encodeName() 和 decodeName() 函数, 在 Unicode 文件名和 8 位文件名之间转换.

Unix 有一些特殊的系统文件 (如. /proc目录下的文件), 对于这些文件, size() 一直返回 0, 但是你仍然可以读取到数据; 这些数据在你调用 read()时, 实时生成. 这种情况下, 你不能使用 atEnd() 判断文件是否到底结尾 ( atEnd() 总是返回 true). 相反, 你应该连续调用 readAll(), read(), readLine(), 直到没有数据. 如下示例, 使用 QTextStream 逐行读取 /proc/modules 文件:


      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() 信号. 这个实现细节意味 QFile 不适用于读写某些特定类型的文件, 比如 Unix 上的设备文件.

平台相关信息

在类 Unix 和 Windows 上, 文件权限的处理不同. 在类 Unix 系统上, 一个不 可写的目录不能创建文件. 但对于 Windows 并不一定如此, 例如 'My Documents' 目录通常不可写, 但是仍然可以创建文件.

Qt对文件权限的理解有限制, 尤其对 QFile::setPermissions() 有影响. 在 Windows 上, 仅当没有任何可读标识(Write*)被设置时, Qt 将设置旧版的只读标识. Qt 不会操作访问控制列表(ACLs), 这使得此函数在NTFS卷上基本没用. 对于VFAT格式的 U 盘, 可能有用. 对于 POSIX 的 ACLs 也不会被修改.

参见 QTextStream, QDataStream, QFileInfo, QDir, The Qt Resource System.

成员类型

typedef QFile::DecoderFn

这个类型定义了一个如下形式的函数的指针:


  QString myDecoderFunc(const QByteArray &localFileName);

参见 setDecodingFunction().

成员函数

QFile::QFile()

构造一个 QFile 对象.

QFile::QFile(const QString &name)

构造文件名 name 指定的 QFile 对象.

QFile::QFile(QObject *parent)

构造父对象是 parentQFile 对象.

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

构造文件名是 name, 父对象是 parentQFile 对象.

QFile::~QFile()

销毁 QFile 对象, 必要时自动关闭文件.

bool QFile::copy(const QString &newName)

将当前 fileName() 复制为新文件 newName. 若成功, 返回 true; 否则返回 false.

注意: 若文件 newName 已存在, copy() 返回 false (即. QFile 不会覆盖现有文件).

复制前, Qt 会关闭源文件.

参见 setFileName().

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

重载函数.

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

参见 rename().

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

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

参见 encodeName().

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

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.

参见 fileName() and setFileName().

[virtual] QString QFile::fileName() const

Reimplemented from QFileDevice::fileName().

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

参见 setFileName() and QFileInfo::fileName().

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.

参见 setFileName().

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.

参见 link().

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

Reimplemented from QIODevice::open().

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.

参见 QIODevice::OpenMode and setFileName().

bool QFile::open(FILE *fh, OpenMode mode, 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.

Example:


  #include <stdio.h>

  void printError(const char* msg)
  {
      QFile file;
      file.open(stderr, QIODevice::WriteOnly);
      file.write(msg, qstrlen(msg));        // write to stderr
      file.close();
  }

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

Warning:

  1. If fh does not refer to a regular file, e.g., it is stdin, stdout, or stderr, you may not be able to seek(). size() returns 0 in those cases. See QIODevice::isSequential() for more information.
  2. Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.

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

bool QFile::open(int fd, OpenMode mode, 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.

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

Warning: If fd is not a regular file, e.g, it is 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). In those cases, size() returns 0. See QIODevice::isSequential() for more information.

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

参见 close().

[virtual] Permissions QFile::permissions() const

Reimplemented from QFileDevice::permissions().

参见 setPermissions().

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

This is an overloaded function.

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.

参见 setFileName().

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

参见 remove().

bool QFile::rename(const QString &newName)

Renames the file currently specified by fileName() to newName. Returns true if successful; otherwise returns false.

If a file with the name newName already exists, rename() returns false (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.

参见 setFileName().

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

参见 rename().

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

Reimplemented from QFileDevice::resize().

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

参见 resize().

void QFile::setFileName(const QString &name)

Sets the name of the file. The name can have no path, a relative path, or an absolute path.

Do not call this function if the file has already been opened.

If the file name has no path or a relative path, the path used will be the application's current directory path at the time of the open() call.

Example:


  QFile file;
  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, and QDir.

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

Reimplemented from QFileDevice::setPermissions().

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.

参见 permissions() and setFileName().

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

This is an overloaded function.

Sets the permissions for fileName file to permissions.

[virtual] qint64 QFile::size() const

Reimplemented from QIODevice::size().

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

This function was introduced in Qt 4.2.

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.

This function was introduced in Qt 4.2.

参见 fileName() and setFileName().