Qt读写文件的简单封装


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>   
  2.   
  3. class RWFile  
  4. {  
  5. public:  
  6.     /* 
  7.     fileName: 要读写的文件名 
  8.     text: 要写入(或被写入的字符串) 
  9.     codec: 文字编码 
  10.     返回值: 失败就返回false, 成功则返回true 
  11.     */  
  12.     static bool ReadAllText(const QString &fileName, QString &text,  
  13.         const char *codec=NULL);  
  14.     static bool WriteAllText(const QString &fileName, const QString &text,  
  15.         const char *codec=NULL);  
  16.     static bool AppendAllText(const QString &fileName, const QString &text,  
  17.         const char *codec=NULL);  
  18. };  
  19.   
  20. bool RWFile::ReadAllText(const QString &fileName, QString &text, const char *codec)  
  21. {  
  22.     QFile file(fileName);  
  23.     if( !file.open(QIODevice::ReadOnly) )  
  24.         return false;  
  25.     QTextStream in(&file);  
  26.     if( codec != NULL )  
  27.         in.setCodec(codec);  
  28.     text = in.readAll();  
  29.     file.close();  
  30.     return true;  
  31. }  
  32.   
  33. bool RWFile::WriteAllText(const QString &fileName, const QString &text, const char *codec)  
  34. {  
  35.     QFile file(fileName);  
  36.     if( !file.open(QIODevice::WriteOnly) )  
  37.         return false;  
  38.     QTextStream out(&file);  
  39.     if( codec != NULL )  
  40.         out.setCodec(codec);  
  41.     out << text;  
  42.     file.close();  
  43.     return true;  
  44. }  
  45.   
  46. bool RWFile::AppendAllText(const QString &fileName, const QString &text, const char *codec)  
  47. {  
  48.     QFile file(fileName);  
  49.     if( !file.open(QIODevice::Append) )  
  50.         return false;  
  51.     QTextStream out(&file);  
  52.     if( codec != NULL )  
  53.         out.setCodec(codec);  
  54.     out << text;  
  55.     file.close();  
  56.     return true;  
  57. }  
  58.   
  59. int main(int argc, char **argv)  
  60. {  
  61.     QCoreApplication app(argc, argv);  
  62.     QString temp("abcde");  
  63.     bool ok1, ok2, ok3;  
  64.     ok1 = RWFile::WriteAllText("abc.txt", temp, "UTF-8");  
  65.     ok2 = RWFile::AppendAllText("abc.txt", temp, "UTF-8");  
  66.     ok3 = RWFile::ReadAllText("abc.txt", temp, "UTF-8");  
  67.     if( ok1 && ok2 && ok3 )  
  68.     {  
  69.         qDebug() << temp;  
  70.     }  
  71.     return 0;  
  72. }  

相关内容