Qt读写文件的简单封装
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
补充:软件开发 , C++ ,