QFile Class Reference

[ QtCore module]

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

继承 QIODevice .

Inherited by QTemporaryFile .

类型

方法

Static Methods


详细描述

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 (),和 ungetChar (), which work one character at a time.

The size of the file is returned by size (). You can get the current file position 使用 pos (), or move to a new file position using seek (). If you've reached the end of the file, atEnd () returns true.

直接读取文件

The following example reads a text file line by line:

     QFile file("in.txt");
     if (!file.open(QIODevice.ReadOnly | QIODevice.Text))
         return;
     while (!file.atEnd()) {
         QByteArray line = file.readLine();
         process_line(line);
     }
			

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

     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 使用 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 () 到 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 does not emit the 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 平台。

平台具体问题

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.


类型文档编制

QFile.FileError

此枚举描述可能的错误,错误返回通过 error () 函数。

常量 描述
QFile.NoError 0 没有发生错误。
QFile.ReadError 1 An error occurred when reading from the 文件。
QFile.WriteError 2 An error occurred when writing to the 文件。
QFile.FatalError 3 发生致命错误。
QFile.ResourceError 4  
QFile.OpenError 5 The file could not be opened.
QFile.AbortError 6 The operation was aborted.
QFile.TimeOutError 7 发生超时。
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 改变。
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.

QFile.FileHandleFlag

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

常量 描述
QFile.AutoCloseHandle 0x0001 The file handle passed into open () should be closed by close (), the default behaviour is that close just flushes the file and the application is responsible for closing the file handle. When opening a file by name, this flag is ignored as Qt always "owns" the file handle and must close it.
QFile.DontCloseHandle 0 The file handle passed into open () will not be closed by Qt. The application must ensure that close () 被调用。

该枚举在 Qt 4.8 引入或被修改。

FileHandleFlags 类型是 typedef 对于 QFlags <FileHandleFlag>. It stores an OR combination of FileHandleFlag values.

QFile.MemoryMapFlags

This enum describes special options that may be used by the map () 函数。

常量 描述
QFile.NoOptions 0 没有选项。

该枚举在 Qt 4.4 引入或被修改。

QFile.Permission

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.

常量 描述
QFile.ReadOwner 0x4000 The file is readable by the owner of the 文件。
QFile.WriteOwner 0x2000 The file is writable by the owner of the 文件。
QFile.ExeOwner 0x1000 The file is executable by the owner of the 文件。
QFile.ReadUser 0x0400 文件对于用户是可读的。
QFile.WriteUser 0x0200 文件对于用户是可写的。
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.

警告: Because of differences in the platforms supported by Qt, the semantics of ReadUser, WriteUser and ExeUser are platform-dependent: On Unix, the rights of the owner of the file are returned and on Windows the rights of the current user are returned. This behavior might change in a future Qt version.

Note that Qt does not by default check for permissions on NTFS file systems, as this may decrease the performance of file handling considerably. It is possible to force permission checking on NTFS by including the following code in your source:

 extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
			

Permission checking is then turned on and off by incrementing and decrementing qt_ntfs_permission_lookup by 1.

 qt_ntfs_permission_lookup++; // turn checking on
 qt_ntfs_permission_lookup--; // turn it off again
			

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


方法文档编制

QFile.__init__ ( self )

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

QFile.__init__ ( self , QString  name )

QFile.__init__ ( self , QObject   parent )

parent argument, if not None, causes self to be owned by Qt instead of PyQt.

构造新文件对象采用给定 parent .

QFile.__init__ ( self , QString  name , QObject   parent )

parent argument, if not None, causes self to be owned by Qt instead of PyQt.

构造新文件对象采用给定 parent to represent the file with the specified name .

bool QFile.atEnd ( self )

重实现自 QIODevice.atEnd ().

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.

QFile.close ( self )

重实现自 QIODevice.close ().

调用 QFile.flush () and closes the file. Errors from flush are ignored.

另请参阅 QIODevice.close ().

bool QFile.copy ( self , QString  newName )

拷贝目前指定的文件通过 fileName () 到文件称为 newName . Returns true if successful; otherwise returns false.

注意:若文件采用名称 newName already exists, copy() returns false (i.e. QFile will not overwrite it).

关闭源文件在拷贝它之前。

另请参阅 setFileName ().

bool QFile.copy (QString  fileName , QString  newName )

这是重载函数。

拷贝文件 fileName to newName . Returns true if successful; otherwise returns false.

若文件采用名称 newName already exists, copy () returns false (i.e., QFile 不会覆写它)。

另请参阅 rename ().

QString QFile.decodeName ( QByteArray   localFileName )

这做反向 QFile.encodeName () 使用 localFileName .

另请参阅 setDecodingFunction () 和 encodeName ().

QString QFile.decodeName (str  localFileName )

这是重载函数。

返回 Unicode 版本为给定 localFileName . 见 encodeName () for details.

QByteArray QFile.encodeName (QString  fileName )

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.

另请参阅 decodeName () and setEncodingFunction ().

FileError QFile.error ( self )

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.

另请参阅 unsetError ().

bool QFile.exists ( self )

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

bool QFile.exists (QString  fileName )

这是重载函数。

Returns true if the file specified by fileName () 存在;否则返回 false.

另请参阅 fileName () 和 setFileName ().

QAbstractFileEngine QFile.fileEngine ( self )

QString QFile.fileName ( self )

返回名称,设置通过 setFileName () or to the QFile 构造函数。

另请参阅 setFileName () 和 QFileInfo.fileName ().

bool QFile.flush ( self )

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

int QFile.handle ( self )

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.

On Symbian, this function returns -1 if the file was opened normally, as Symbian OS native file handles do not fit in an int, and are incompatible with C library functions that the handle would be used for. If the file was opened using the overloads that take an open C library file handle / file descriptor, then this function returns that same handle.

另请参阅 QSocketNotifier .

bool QFile.isSequential ( self )

重实现自 QIODevice.isSequential ().

Returns true if the file can only be manipulated sequentially; otherwise returns false.

Most files support random-access, but some special files may not.

另请参阅 QIODevice.isSequential ().

bool QFile.link ( self , QString  newName )

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 .

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

注意: Symbian filesystem does not support links.

另请参阅 setFileName ().

bool QFile.link (QString  oldname , QString  newName )

这是重载函数。

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

sip.voidptr QFile.map ( self , int  offset , int  size , MemoryMapFlags   flags  = QFile.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. 当 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.

注意: On Windows CE 5.0 the file will be closed before mapping occurs.

该函数在 Qt 4.4 引入。

另请参阅 unmap () 和 QAbstractFileEngine.supportsExtension ().

bool QFile.open ( self , QIODevice.OpenMode   flags )

重实现自 QIODevice.open ().

打开文件使用 OpenMode mode , returning true if successful; otherwise false.

mode 必须是 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 ().

bool QFile.open ( self , int  fd , QIODevice.OpenMode   flags )

bool QFile.open ( self , int  fd , QIODevice.OpenMode   flags , FileHandleFlags   handleFlags )

Permissions QFile.permissions ( self )

Returns the complete OR-ed together combination of QFile.Permission 为 文件。

另请参阅 setPermissions () 和 setFileName ().

Permissions QFile.permissions (QString  filename )

这是重载函数。

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

int QFile.pos ( self )

重实现自 QIODevice.pos ().

str QFile.readData ( self , int  maxlen )

重实现自 QIODevice.readData ().

str QFile.readLineData ( self , int  maxlen )

重实现自 QIODevice.readLineData ().

QString QFile.readLink ( self )

QString QFile.readLink (QString  fileName )

bool QFile.remove ( self )

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

The file is closed before it is removed.

另请参阅 setFileName ().

bool QFile.remove (QString  fileName )

这是重载函数。

Removes the file specified by the fileName 给定。

Returns true if successful; otherwise returns false.

另请参阅 remove ().

bool QFile.rename ( self , QString  newName )

Renames the file currently specified by fileName () 到 newName 。返回 true if successful; otherwise returns false.

若文件采用名称 newName already exists, rename() returns false (i.e., QFile will not overwrite it).

The file is closed before it is renamed.

另请参阅 setFileName ().

bool QFile.rename (QString  oldName , QString  newName )

这是重载函数。

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

若文件采用名称 newName already exists, rename () returns false (i.e., QFile 不会覆写它)。

另请参阅 rename ().

bool QFile.resize ( self , int  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.

另请参阅 size () 和 setFileName ().

bool QFile.resize (QString  filename , int  sz )

这是重载函数。

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

bool QFile.seek ( self , int  offset )

重实现自 QIODevice.seek ().

For random-access devices, this function sets the current position to pos , returning true on success, or false if an error occurred. For sequential devices, the default behavior is to do nothing and return false.

Seeking beyond the end of a file: If the position is beyond the end of a file, then seek() shall not immediately extend the file. If a write is performed at this position, then the file shall be extended. The content of the file between the previous end of file and the newly written data is UNDEFINED and varies between platforms and file systems.

QFile.setFileName ( self , QString  name )

设置 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 .

bool QFile.setPermissions ( self , Permissions   permissionSpec )

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

另请参阅 permissions () 和 setFileName ().

bool QFile.setPermissions (QString  filename , Permissions   permissionSpec )

这是重载函数。

设置权限为 fileName file to permissions .

int QFile.size ( self )

重实现自 QIODevice.size ().

返回文件大小。

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

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.

该函数在 Qt 4.2 引入。

QString QFile.symLinkTarget (QString  fileName )

这是重载函数。

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.

该函数在 Qt 4.2 引入。

另请参阅 fileName () 和 setFileName ().

bool QFile.unmap ( self , sip.voidptr  address )

取消映射内存 address .

Returns true if the unmap succeeds; false otherwise.

该函数在 Qt 4.4 引入。

另请参阅 map () 和 QAbstractFileEngine.supportsExtension ().

QFile.unsetError ( self )

把文件的错误设为 QFile.NoError .

另请参阅 error ().

int QFile.writeData ( self , str  data )

重实现自 QIODevice.writeData ().