手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Qt读写文件的简单封装

[日期:2012-07-30] 来源:Linux社区  作者:aaa20090987 [字体:大 中 小]

C#中,有下列函数可以简单地读写文件:
读:  temp = File.ReadAllText("abc.txt",Encoding.Default); 
写:  File.WriteAllText("abc.txt", temp, Encoding.Default);
追加: File.AppendAllText("abc.txt", temp, Encoding.Default);

现在我也来用Qt彷写一个,以后读写简单的文本文件就不用这么麻烦啦。

  1. #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;  
  • }  
  • linux
    相关资讯       Qt 
    本文评论   查看全部评论 (0)
    表情: 表情 姓名: 字数

           

    评论声明
    • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
    • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
    • 本站管理人员有权保留或删除其管辖留言中的任意内容
    • 本站有权在网站内转载或引用您的评论
    • 参与本评论即表明您已经阅读并接受上述条款