当先锋百科网

首页 1 2 3 4 5 6 7

QFile Class Qt官方文档

细节描述

QFile类提供了一个从文件读写的接口。

QFile是一个可供读写文档和二进制文件资源的IO设备,它一般被他自己使用,更方便的是通过QTextStream和QDataStream。

文件的名字通常是通过构造函数来传递,当然也可以随时通过使用setFileName().函数实现。无论在什么操作系统下,QFile都最好使用”/”作为文件路径分隔符,而不是使用windows系统下的”\”,这也是不支持的。

你可以使用exists()来检查文件是否存在,使用remove()删除一个文件。(更高级的文件系统操作由QFileInfo和QDir提供)

文件打开使用open(),关闭使用close(),刷新内存数据到磁盘使用flush(),close()关闭文件也会刷新内存缓存到磁盘的哦。数据Data的读写通常使用QDataStream或者QTextStream,当然也可以通过调用继承自QIODevice的函数read(),readLine(),realAll(),write()等。同时,QFile也集成了getChar(),putChar()和ungetChar(),这些都是一次处理一个字符的。

文件的大小size通过size()函数返回。你可以使用pos()获得当前文件的位置,或者通过seek()来重定位。如果到达文件的末尾,atEnd()函数将返回true。

直接读取文件

下面的例子从一个文本文件in.txt中一行接一行地读取文件:

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”) (line terminators)转换(convert)成c++风格的行终止符(“\n”)。 默认情况下,QFile假定(assume) 为二进制,也就是说(i.e.),它不会在文件按字节存储时执行(perform)任何 转换(conversion)。

使用流(Stream)读取文件

接下来的例子使用能够QTextStream来一行一行地读取文件

QFile file("in.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text) )
    return;
QTextStream in(&file);  //将file对应的文件与in绑定
while(!in.atEnd()){
    QString line = in.readLine();
    process_line(line); //对读取的行数据进行处理的伪代码
}

QTextStream类会比较注重将储存在磁盘上的8-bit数据转化成一个16位的Unicode型的QString。默认情况下,它会使用用户系统本地的8-bit编码格式(例如:在大多数的类unix操作系统上使用的是 UTF-8编码)。当然,这个也是可以通过QTextStream::setCodec()来改变。

想要写文档,我们可以使用<<()操作符实现,这是运算符重载来实现将“<<”右边的数据变量写到左边的QTextStream对象中:

QFile file("out.txt");
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    return;
QTextStream out(&file);
out << "The magic number is :" <<  << "\n";

同理,使用QDataStream是类似的,具体的使用参见它的文档。

当你在Qt下使用QFile, QFileInfo,和QDir区访问文件系统时,你可以使用Unicode文件名。在Unix中,这些文件名都会被转换成8-bit编码的。如果你想使用标准C++接口( cstdio or iostream)或者其他平台接口而不是QFile去访问文件的话,你可以使用encodeName()和decodeName()函数在两者之间转换。

在Unix上,有一些特殊的系统文件(比如在/proc中),使用size()总是会返回0,但是还是可以从这些文件读到内容,这些内容是你在调用read()是直接生成的数据。因此在这种情况下,你不能使用atEnd()函数来确定(determine)是否还有数据可读(因为atEnd()仍然会返回true来申明一个文件的大小size=0)。相应的,你应该调用readAll()或者重复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();
}

信号signals

不像其他的QIODevice的继承类(例如QTcpSocket),QFile不会发送aboutToClose(), byteWritten()或者readyRead()信号。这个细节就意味着QFile不适合用于读写类似于unix中的设备文件的文件。

Platform Specific Issues平台的具体问题

windows和 unix的文件权限管理是不同的。在类unix系统中的没有可写权限的目录中是不能创建文件的。但在windows系统中就不是这样的了,文件夹不可写,但是可以在其内部创建文件。

qt对于文件权限的理解是有局限性的,这就影响了尤其是像QFile::setPermissions()这样的函数。在windows中,当没有写相关的标志传递时,只会设置传统的只读标志。Qt不会更改访问控制列表(access control list– ACL ),这也就是的这个函数队NTFS文件系统几乎不管用了。但对于使用的VFAT格式的USB还是可用的。 POSIX ACL也不能更改。

Member Function Documentation

QFile()

QFile::QFile()

Constructs a QFile object.

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::~QFile()

Destroys the file object, closing it if necessary.

copy

bool QFile::copy(const QString &newName)

Copies the file currently specified by fileName() to a file called newName. Returns true if successful; otherwise returns false.
Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it).
The source file is closed before it is copied.
See also setFileName().

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

This is an overloaded function.
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).
See also rename().

decodeName

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

This does the reverse of QFile::encodeName() using localFileName.
See also 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.

encodeName()

[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.
See also decodeName().

exists

[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.
See also fileName() and setFileName().

fileName

[virtual] QString QFile::fileName() const

Reimplemented from QFileDevice::fileName().
Returns the name set by setFileName() or to the QFile constructors.
See also setFileName() and QFileInfo::fileName().

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.
See also setFileName().

[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.
See also link().

open

[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.
See also 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:
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.
Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
Note: For Windows CE you may not be able to call resize().
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:

See also 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: For Windows CE you may not be able to call seek(), and size() returns 0.
Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
See also close().

permissions

[virtual] Permissions QFile::permissions() const

Reimplemented from QFileDevice::permissions().
See also 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.

remove

bool QFile::remove()

Removes the file specified by fileName(). Returns true if successful; otherwise returns false.
The file is closed before it is removed.
See also setFileName().

[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.
See also remove().

rename

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.
See also 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).
See also rename().

resize

[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.
See also resize().

setFilename

void QFile::setFileName(const QString &name)

Sets the name of the file. The name can have no path, a relative path, or an absolute path.
Do not call this function if the file has already been opened.
If the file name has no path or a relative path, the path used will be the application’s current directory path at the time of the open() call.
Example:

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

Note that the directory separator “/” works for all operating systems supported by Qt.
See also fileName(), QFileInfo, and QDir.

setPermissions

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

size

[virtual] qint64 QFile::size() const

Reimplemented from QIODevice::size().

symLinkTarget

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