CZipSaver.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. int status = 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. if(status != ZIP_OK)
  29. throw new std::runtime_error("CZipOutputStream: zipOpenNewFileInZip failed");
  30. owner->activeStream = this;
  31. }
  32. CZipOutputStream::~CZipOutputStream()
  33. {
  34. zipCloseFileInZip(handle);
  35. owner->activeStream = nullptr;
  36. }
  37. si64 CZipOutputStream::write(const ui8 * data, si64 size)
  38. {
  39. int ret = zipWriteInFileInZip(handle, (const void*)data, (unsigned)size);
  40. if (ret == ZIP_OK)
  41. return size;
  42. else
  43. return 0;
  44. }
  45. ///CZipSaver
  46. CZipSaver::CZipSaver(std::shared_ptr<CIOApi> api, const std::string & path):
  47. ioApi(api),
  48. zipApi(ioApi->getApiStructure()),
  49. handle(nullptr),
  50. activeStream(nullptr)
  51. {
  52. handle = zipOpen2_64(path.c_str(), APPEND_STATUS_CREATE, nullptr, &zipApi);
  53. if (handle == nullptr)
  54. throw new std::runtime_error("CZipSaver: Failed to create archive");
  55. }
  56. CZipSaver::~CZipSaver()
  57. {
  58. if(activeStream != nullptr)
  59. {
  60. logGlobal->error("CZipSaver::~CZipSaver: active stream found");
  61. zipCloseFileInZip(handle);
  62. }
  63. if(handle != nullptr)
  64. zipClose(handle, nullptr);
  65. }
  66. std::unique_ptr<COutputStream> CZipSaver::addFile(const std::string & archiveFilename)
  67. {
  68. if(activeStream != nullptr)
  69. throw new std::runtime_error("CZipSaver::addFile: stream already opened");
  70. std::unique_ptr<COutputStream> stream(new CZipOutputStream(this, handle, archiveFilename));
  71. return std::move(stream);
  72. }