C#中,有下列函數可以簡單地讀寫文件:
讀: temp = File.ReadAllText("abc.txt",Encoding.Default);
寫: File.WriteAllText("abc.txt", temp, Encoding.Default);
追加: File.AppendAllText("abc.txt", temp, Encoding.Default);
現在我也來用Qt彷寫一個,以後讀寫簡單的文本文件就不用這麼麻煩啦。
[cpp]
#include <QtCore>
class RWFile
{
public:
/*
fileName: 要讀寫的文件名
text: 要寫入(或被寫入的字符串)
codec: 文字編碼
返回值: 失敗就返回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);
};
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;
}
return 0;
}
作者:AAA20090987