QFile 類

QFile 類提供用於讀寫文件的接口。 更多...

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

QTemporaryFile

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

公共類型

typedef DecoderFn

公共函數

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

重實現公共函數

virtual QString fileName () const override
virtual bool open (QIODevice::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 )
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 )
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 繼承函數 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 () 告訴 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 位數據轉換成 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 類似,可以使用操作符 <<() 寫入數據,和使用操作符 >>() 讀迴它。見類文檔編製,瞭解細節。

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.

在 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 不會發射 aboutToClose (), bytesWritten (),或 readyRead () 信號。此實現細節意味著 QFile 不適閤讀寫某些類型的文件,譬如 Unix 平颱中的設備文件。

平颱具體問題

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

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

在 Android,會應用一些局限性當處理 內容 URI (統一資源標識符) :

  • 可能需要提示用戶的訪問權限透過 QFileDialog which implements Android's native file picker.
  • 目標是遵循 作用域存儲 指導方針 (譬如:使用 App 特定目錄,而不是其它公共外部目錄)。更多信息,另請參閱 存儲最佳實踐 .
  • 由於 Qt API (如 QFile) 的設計,是不可能的,完全集成後者 API 與 Android 的 MediaStore API。

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

成員類型文檔編製

typedef QFile:: DecoderFn

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

QString myDecoderFunc(const QByteArray &localFileName);
					

另請參閱 setDecodingFunction ().

成員函數文檔編製

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

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

QFile:: QFile ( QObject * parent )

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

QFile:: QFile (const QString & name )

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

QFile:: QFile ()

構造 QFile 對象。

[虛擬] QFile:: ~QFile ()

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

bool QFile:: copy (const QString & newName )

拷貝文件命名 fileName () 到 newName .

此文件被關閉,在拷貝它之前。

若拷貝的文件是 symlink (符號鏈接),拷貝的就是它引用的文件,而不是鏈接本身。除拷貝權限外,不會拷貝其它文件元數據。

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

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

注意: 在 Android,此操作尚不支持 content 方案 URI (統一資源標識符)。

另請參閱 setFileName ().

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

這是重載函數。

拷貝文件命名 fileName to newName .

此文件被關閉,在拷貝它之前。

若拷貝的文件是 symlink (符號鏈接),拷貝的就是它引用的文件,而不是鏈接本身。除拷貝權限外,不會拷貝其它文件元數據。

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

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

注意: 在 Android,此操作尚不支持 content 方案 URI (統一資源標識符)。

另請參閱 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 ().

[override virtual] QString QFile:: fileName () const

重實現: QFileDevice::fileName () const.

返迴的名稱設置通過 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:: moveToTrash ()

移動指定文件按 fileName () 到垃圾桶。返迴 true 若成功,並設置 fileName () 為可以在垃圾桶中找到的文件路徑;否則返迴 false .

注意: 在係統 API 不報告垃圾桶中文件位置的係統中, fileName () 會被設為 null 字符串,一旦移動文件。在沒有垃圾桶的係統中,此函數始終返迴 false。

該函數在 Qt 5.15 引入。

[static] bool QFile:: moveToTrash (const QString & fileName , QString * pathInTrash = nullptr)

這是重載函數。

移動指定文件按 fileName () 到垃圾桶。返迴 true 若成功,並設置 pathInTrash (若有提供) 為可以在垃圾桶中找到的文件路徑;否則返迴 false .

注意: 在係統 API 不報告垃圾桶中文件路徑在哪裏的係統中, pathInTrash 會被設為 null 字符串,一旦移動文件。在沒有垃圾桶的係統中,此函數始終返迴 false。

該函數在 Qt 5.15 引入。

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

重實現: QIODevice::open (QIODevice::OpenMode mode).

打開文件使用 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. On Android, it's expected to have access permission to the parent of the file name, otherwise, it won't be possible to create this non-existing file.

另請參閱 QIODevice::OpenMode and setFileName ().

bool QFile:: open ( FILE * fh , QIODevice::OpenMode mode , QFileDevice::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 , QIODevice::OpenMode mode , QFileDevice::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 () 不會實際關閉文件,而僅刷新它。

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

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

另請參閱 close ().

[override virtual] QFileDevice::Permissions QFile:: permissions () const

重實現: QFileDevice::permissions () const.

另請參閱 setPermissions ().

[static] QFileDevice::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 已存在,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 到大小 (以字節為單位) 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 .

[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 文件到 permissions .

[override virtual] qint64 QFile:: size () const

重實現: QFileDevice::size () const.

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