C# 的 File 類別提供了 ReadAllText、WriteAllText、AppendAllText 三個一行的 API,讀寫文字檔非常乾脆。改用 Qt 開發時少了這層糖,每次都要自己開 QFile、建 QTextStream、處理編碼,寫久了不免覺得囉嗦。既然如此,不如自己包一個同樣風格的工具類別。
三個靜態方法,分別對應「全部讀入」、「全部覆寫」、「接在後面追加」。每個方法都接受檔名、文字內容與編碼名稱,成功回傳 true,失敗回傳 false,讓呼叫端不必被例外流程打斷。
#include <QtCore>
class RWFile
{
public:
/*
fileName: 要讀寫的檔案名稱
text: 要寫入(或被寫入)的字串
codec: 文字編碼,傳 NULL 則使用系統預設
回傳值: 失敗回傳 false,成功回傳 true
*/
static bool ReadAllText(const QString &fileName, QString &text,
const char *codec = NULL);
static bool WriteAllText(const QString &fileName, const QString &text,
const char *codec = NULL);
static bool AppendAllText(const QString &fileName, const QString &text,
const char *codec = NULL);
};
三者的骨架幾乎一樣:開檔、建立 QTextStream、需要時指定編碼、讀或寫、關檔。差別只在開檔模式——唯讀、唯寫、附加。
bool RWFile::ReadAllText(const QString &fileName, QString &text, const char *codec)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
QTextStream in(&file);
if (codec != NULL)
in.setCodec(codec);
text = in.readAll();
file.close();
return true;
}
bool RWFile::WriteAllText(const QString &fileName, const QString &text, const char *codec)
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
return false;
QTextStream out(&file);
if (codec != NULL)
out.setCodec(codec);
out << text;
file.close();
return true;
}
bool RWFile::AppendAllText(const QString &fileName, const QString &text, const char *codec)
{
QFile file(fileName);
if (!file.open(QIODevice::Append))
return false;
QTextStream out(&file);
if (codec != NULL)
out.setCodec(codec);
out << text;
file.close();
return true;
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QString temp("abcde");
bool ok1, ok2, ok3;
ok1 = RWFile::WriteAllText("abc.txt", temp, "UTF-8");
ok2 = RWFile::AppendAllText("abc.txt", temp, "UTF-8");
ok3 = RWFile::ReadAllText("abc.txt", temp, "UTF-8");
if (ok1 && ok2 && ok3)
qDebug() << temp; // 預期輸出 abcdeabcde
return 0;
}
三個呼叫都成功時,abc.txt 的內容會是兩段 "abcde" 相接,讀回來的 temp 也就等於 abcdeabcde。這個小類別只依賴 QtCore,因此放在主控台程式或服務程式中都能直接使用;若日後需要處理超大檔案,再改成 QFile::readAll 搭配分塊讀取即可。