QFile 類

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

頭: #include <QFile>
qmake: QT += core
繼承: QFileDevice
繼承者: QTemporaryFile

注意: 此類的所有函數 可重入 .

公共類型

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

額外繼承成員

詳細描述

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 QFile 可以單獨使用,或更方便一起使用與 QTextStream or QDataStream .

通常在構造函數中傳遞文件名,但可以隨時設置它使用 setFileName (). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.

可以檢查文件是否存在使用 exists (),和移除文件使用 remove ()。(更高級的文件係統相關操作的提供由 QFileInfo and QDir )。

打開文件采用 open (),關閉采用 close (),和刷新采用 flush ()。數據的讀寫通常是使用 QDataStream or QTextStream ,但也可以調用 QIODevice 繼承函數 read (), readLine (), readAll (), write (). QFile 還繼承 getChar (), putChar (),和 ungetChar (),每次操控一字符。

文件大小的返迴是通過 size ()。可以獲取當前文件位置使用 pos (),或移至新文件位置使用 seek ()。若已到達 EOF (文件末尾), 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.

使用流讀取文件

下一範例使用 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 位數據轉換成 16 位 Unicode QString . By default, it assumes that the user system's local 8-bit encoding is used (e.g., UTF-8 on most unix based operating systems; see QTextCodec::codecForLocale () for details). This can be changed using QTextStream::setCodec ().

要寫入文本,可以使用操作符 <<(),重載以接受 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 類似,可以使用操作符 <<() 寫入數據,和使用操作符 >>() 讀迴它。見類文檔編製,瞭解細節。

當使用 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.

在 Unix,有一些特殊係統文件 (如在 /proc ) 其中 size () 將始終返迴 0,仍然可以從這種文件讀取更多數據;直接生成數據是為響應調用 read ()。在此情況下,不管怎樣,不可以使用 atEnd () 以確定是否有更多數據要讀取 (由於 atEnd () 將返迴 true 對於聲明擁有大小 0 的文件)。相反,應該調用 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 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 platforms.

平颱具體問題

文件權限的處理是不同的,在像 Unix 係統和 Windows。在非 writable 目錄像 Unix 係統,無法創建文件。在 Windows 並不始終如此,例如,"我的文檔" 目錄通常不可寫,但可以在其中創建文件仍然是可能的。

Qt 對文件權限的理解是有限的,這尤其影響 QFile::setPermissions () 函數。在 Windows,Qt 將隻設置遺留隻讀標誌,且僅當未傳遞 Write* 標誌時。Qt 不操縱 ACL (訪問控製列錶),這使得此函數對 NTFS 捲幾乎無用。它仍然可以用於使用 VFAT 文件係統的 U 盤。也不操縱 POSIX ACL。

另請參閱 QTextStream , QDataStream , QFileInfo , QDir ,和 Qt 資源係統 .

成員類型文檔編製

typedef QFile:: DecoderFn

這是采用以下簽名的函數指針的 typedef:

QString myDecoderFunc(const QByteArray &localFileName);
					

另請參閱 setDecodingFunction ().

成員函數文檔編製

QFile:: QFile ()

構造 QFile 對象。

QFile:: QFile (const QString & name )

構造新文件對象以錶示文件采用給定 name .

QFile:: QFile ( QObject * parent )

構造新文件對象采用給定 parent .

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

構造新文件對象采用給定 parent 錶示文件采用指定 name .

QFile:: ~QFile ()

銷毀文件對象,關閉它若有必要。

bool QFile:: copy (const QString & newName )

拷貝目前指定的文件通過 fileName () 到文件稱為 newName 。返迴 true 若成功;否則返迴 false .

注意:若文件采用名稱 newName 已存在,copy() 返迴 false (即 QFile 不會覆寫它)。

關閉源文件在拷貝它之前。

另請參閱 setFileName ().

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

這是重載函數。

拷貝文件 fileName to newName 。返迴 true 若成功;否則返迴 false .

若文件采用名稱 newName already exists, copy () 返迴 false (即, QFile 不會覆寫它)。

另請參閱 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。

bool QFile:: exists () const

這是重載函數。

返迴 true 若文件指定通過 fileName () 存在;否則返迴 false .

另請參閱 fileName () 和 setFileName ().

[虛擬] QString QFile:: fileName () const

重實現自 QFileDevice::fileName ().

返迴的名稱設置通過 setFileName () 或到 QFile 構造函數。

另請參閱 setFileName () 和 QFileInfo::fileName ().

創建鏈接命名 linkName 指嚮文件目前指定通過 fileName ()。鏈接是什麼從屬底層文件係統 (不管是 Windows 快捷方式,還是 Unix 符號鏈接)。返迴 true 若成功;否則返迴 false .

此函數不會覆寫文件係統中已存在的實體;在此情況下, link() 將返迴 false 並設置 error() to return RenameError .

注意: 要在 Windows 創建有效鏈接, linkName 必須擁有 .lnk 文件擴展名。

另請參閱 setFileName ().

這是重載函數。

創建鏈接命名 linkName 指嚮文件 fileName 。鏈接是什麼從屬底層文件係統 (不管是 Windows 快捷方式,還是 Unix 符號鏈接)。返迴 true 若成功;否則返迴 false .

另請參閱 link ().

[虛擬] bool QFile:: open ( OpenMode mode )

重實現自 QIODevice::open ().

打開文件使用 OpenMode mode ,返迴 true,若成功;否則返迴 false。

The mode 必須為 QIODevice::ReadOnly , QIODevice::WriteOnly ,或 QIODevice::ReadWrite 。它還可以擁有額外標誌,譬如 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 ( FILE * fh , OpenMode mode , FileHandleFlags handleFlags = DontCloseHandle)

這是重載函數。

打開現有文件句柄 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 是使用此函數打開的,行為對於 close () is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified, and this function succeeds, then calling close () 會關閉采納句柄。否則, close () 不會實際關閉文件,而僅刷新它。

警告:

  1. fh 不是指常規文件,如,它是 stdin , stdout ,或 stderr ,可能無法 seek (). size () 返迴 0 在此情況下。見 QIODevice::isSequential () 瞭解更多信息。
  2. 由於此函數打開文件不用指定文件名,所以,無法使用此 QFile 采用 QFileInfo .

Windows 平颱注意事項

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 。順序設備 (譬如:stdin 和 stdout) 不受此局限性的影響。

需要啓用對控製颱應用程序的支持,為在控製颱使用 stdin (標準輸入)、stdout (標準輸齣) 及 stderr (標準錯誤) 流。要做到這,把以下聲明添加到應用程序工程文件:

CONFIG += console
					

另請參閱 close ().

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

這是重載函數。

打開現有文件描述符 fd 以給定 mode . handleFlags 可以用於指定額外選項。返迴 true 若成功;否則返迴 false .

QFile 是使用此函數打開的,行為對於 close () is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified, and this function succeeds, then calling close () 會關閉采納句柄。否則, close () 不會實際關閉文件,而僅刷新它。

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.

警告: fd 不是常規文件,如為 0 ( stdin ), 1 ( stdout ),或 2 ( stderr ),可能無法 seek ()。在此情況下, size () 返迴 0 。見 QIODevice::isSequential () 瞭解更多信息。

警告: 由於此函數打開文件不用指定文件名,所以,無法使用此 QFile 采用 QFileInfo .

另請參閱 close ().

[虛擬] Permissions QFile:: permissions () const

重實現自 QFileDevice::permissions ().

另請參閱 setPermissions ().

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

這是重載函數。

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

bool QFile:: remove ()

移除文件指定通過 fileName ()。返迴 true 若成功;否則返迴 false .

文件被關閉,在移除它之前。

另請參閱 setFileName ().

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

這是重載函數。

移除文件指定通過 fileName 給定。

返迴 true 若成功;否則返迴 false .

另請參閱 remove ().

bool QFile:: rename (const QString & newName )

重命名文件目前指定通過 fileName () 到 newName 。返迴 true 若成功;否則返迴 false .

若文件采用名稱 newName 已存在,rename() 返迴 false (即, QFile 不會覆寫它)。

文件關閉,在重命名之前。

若重命名操作失敗,Qt 將試圖把此文件的內容拷貝到 newName ,然後移除此文件,僅保持 newName 。若該拷貝操作失敗 (或無法移除此文件),目的地文件 newName 被移除以還原舊狀態。

另請參閱 setFileName ().

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

這是重載函數。

重命名文件 oldName to newName 。返迴 true 若成功;否則返迴 false .

若文件采用名稱 newName already exists, rename () 返迴 false (即, QFile 不會覆寫它)。

另請參閱 rename ().

[虛擬] bool QFile:: resize ( qint64 sz )

重實現自 QFileDevice::resize ().

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

這是重載函數。

fileName 到大小 (以字節為單位) sz 。返迴 true 若重置大小成功;否則 false。若 sz > fileName 目前是新字節數將被設為 0,若 sz 更小,隻需截取文件。

警告: 此函數可能失敗,若文件不存在。

另請參閱 resize ().

void QFile:: setFileName (const QString & name )

設置 name 為文件。名稱可以沒有路徑、相對路徑或絕對路徑。

不要調用此函數,若文件已打開。

若文件名沒有路徑 (或相對路徑),使用的路徑將是應用程序的當前目錄路徑 open () 調用。

範例:

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

注意,目錄分隔符 / 工作於由 Qt 支持的所有操作係統。

另請參閱 fileName (), QFileInfo ,和 QDir .

[虛擬] bool QFile:: setPermissions ( Permissions permissions )

重實現自 QFileDevice::setPermissions ().

將文件權限設為 permissions 指定。返迴 true 若成功,或 false 若權限不能被修改。

警告: 此函數不操縱 ACL (訪問控製列錶),這可能限製其有效性。

另請參閱 permissions () 和 setFileName ().

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

這是重載函數。

設置權限為 fileName 文件到 permissions .

[虛擬] qint64 QFile:: size () const

重實現自 QIODevice::size ().

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

返迴符號鏈接 (或 Windows 快捷方式) 引用文件 (或目錄) 的絕對路徑指定通過 fileName ,或返迴空字符串若 fileName 不對應於符號鏈接。

此名稱可能不錶示現有文件;它隻是字符串。 QFile::exists () 返迴 true 若符號鏈接指嚮現有文件。

該函數在 Qt 4.2 引入。

QString QFile:: symLinkTarget () const

這是重載函數。

返迴符號鏈接 (或 Windows 快捷方式) 指嚮文件 (或目錄) 的絕對路徑,或空字符串若對象不是符號鏈接。

此名稱可能不錶示現有文件;它隻是字符串。 QFile::exists () 返迴 true 若符號鏈接指嚮現有文件。

該函數在 Qt 4.2 引入。

另請參閱 fileName () 和 setFileName ().