歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Qt讀寫文件的簡單封裝

Qt讀寫文件的簡單封裝

日期:2017/3/1 10:14:38   编辑:Linux編程

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