TemporaryFile.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (C) 2018 KeePassXC Team <team@keepassxc.org>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 or (at your option)
  7. * version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "TemporaryFile.h"
  18. TemporaryFile::TemporaryFile()
  19. : TemporaryFile(nullptr)
  20. {
  21. }
  22. TemporaryFile::TemporaryFile(const QString& templateName)
  23. : TemporaryFile(templateName, nullptr)
  24. {
  25. }
  26. TemporaryFile::TemporaryFile(QObject* parent)
  27. : QFile(parent)
  28. {
  29. QTemporaryFile tmp;
  30. tmp.open();
  31. QFile::setFileName(tmp.fileName());
  32. tmp.close();
  33. }
  34. TemporaryFile::TemporaryFile(const QString& templateName, QObject* parent)
  35. : QFile(parent)
  36. {
  37. QTemporaryFile tmp(templateName);
  38. tmp.open();
  39. QFile::setFileName(tmp.fileName());
  40. tmp.close();
  41. }
  42. TemporaryFile::~TemporaryFile()
  43. {
  44. remove();
  45. }
  46. bool TemporaryFile::open()
  47. {
  48. return QFile::open(QIODevice::ReadWrite);
  49. }
  50. bool TemporaryFile::copyFromFile(const QString& otherFileName)
  51. {
  52. close();
  53. if (!open(QFile::WriteOnly | QFile::Truncate)) {
  54. return false;
  55. }
  56. QFile otherFile(otherFileName);
  57. if (!otherFile.open(QFile::ReadOnly)) {
  58. close();
  59. return false;
  60. }
  61. QByteArray data;
  62. while (!(data = otherFile.read(1024)).isEmpty()) {
  63. write(data);
  64. }
  65. otherFile.close();
  66. close();
  67. return true;
  68. }