CZipSaver.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * CZipSaver.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CZipSaver.h"
  12. ///CZipOutputStream
  13. CZipOutputStream::CZipOutputStream(CZipSaver * owner_, zipFile archive, const std::string & archiveFilename):
  14. handle(archive),
  15. owner(owner_)
  16. {
  17. //zip_fileinfo fileInfo;
  18. zipOpenNewFileInZip(handle,
  19. archiveFilename.c_str(),
  20. nullptr,//todo: use fileInfo,
  21. nullptr,
  22. 0,
  23. nullptr,
  24. 0,
  25. "",
  26. Z_DEFLATED,
  27. Z_DEFAULT_COMPRESSION);
  28. owner->activeStream = this;
  29. }
  30. CZipOutputStream::~CZipOutputStream()
  31. {
  32. zipCloseFileInZip(handle);
  33. owner->activeStream = nullptr;
  34. }
  35. si64 CZipOutputStream::write(const ui8 * data, si64 size)
  36. {
  37. int ret = zipWriteInFileInZip(handle, (const void*)data, (unsigned)size);
  38. if (ret == ZIP_OK)
  39. return size;
  40. else
  41. return 0;
  42. }
  43. ///CZipSaver
  44. CZipSaver::CZipSaver(std::shared_ptr<CIOApi> api, const std::string & path):
  45. ioApi(api),
  46. zipApi(ioApi->getApiStructure()),
  47. handle(nullptr),
  48. activeStream(nullptr)
  49. {
  50. handle = zipOpen2_64(path.c_str(), APPEND_STATUS_CREATE, nullptr, &zipApi);
  51. if (handle == nullptr)
  52. throw new std::runtime_error("Failed to create archive");
  53. }
  54. CZipSaver::~CZipSaver()
  55. {
  56. if(activeStream != nullptr)
  57. {
  58. logGlobal->error("CZipSaver::~CZipSaver: active stream found");
  59. zipCloseFileInZip(handle);
  60. }
  61. if(handle != nullptr)
  62. zipClose(handle, nullptr);
  63. }
  64. std::unique_ptr<COutputStream> CZipSaver::addFile(const std::string & archiveFilename)
  65. {
  66. if(activeStream != nullptr)
  67. throw new std::runtime_error("CZipSaver::addFile: stream already opened");
  68. std::unique_ptr<COutputStream> stream(new CZipOutputStream(this, handle, archiveFilename));
  69. return std::move(stream);
  70. }