2 * Copyright (C) 2023 Anton Blad
3 * Copyright (C) 2023 Fredrik Kuivinen
4 * Copyright (C) 2023 Jakob Rosén
6 * This file is licensed under GPL v2.
9 // Simple C++ wrapper for minizip
12 #include "ziparchive.h"
13 #include <minizip/unzip.h>
15 ZipArchive::ZipArchive(std::string zipname
)
20 bool ZipArchive::isZipFile() {
21 unzFile zipfile
=unzOpen(filename
.c_str());
28 bool ZipArchive::strEndsWith(const std::string
&str
, const std::string
&suffix
) {
29 if (str
.length()<suffix
.length()) {
32 return str
.compare(str
.length()-suffix
.length(), suffix
.length(), suffix
) == 0;
35 /// return list of filenames in zip archive
36 std::vector
<std::string
> ZipArchive::getFilenames(const std::string suffix
) {
37 std::vector
<std::string
> filenames
;
38 unzFile zip
=unzOpen(filename
.c_str());
40 return filenames
; // Return empty list
42 if (UNZ_OK
== unzGoToFirstFile(zip
)){
44 char itemname
[MAX_FILENAME_LENGTH
];
45 if (UNZ_OK
==unzGetCurrentFileInfo(zip
, NULL
, itemname
, sizeof(itemname
), NULL
, 0, NULL
, 0)) {
46 std::string itemstr
=std::string(itemname
);
47 if (strEndsWith(tolower(itemstr
), tolower(suffix
))) {
48 filenames
.push_back(std::string(itemname
));
51 } while (UNZ_OK
== unzGoToNextFile(zip
));
57 bool ZipArchive::extractItem(const std::string itemName
, struct zip_buffer
* zipbuf
) {
62 unzFile zip
= unzOpen(filename
.c_str());
64 fprintf(stderr
,"ZipArchive: Could not open zip file\n");
68 err
= unzLocateFile(zip
, itemName
.c_str(), 0);
70 fprintf(stderr
, "ZipArchive: Could not locate file in zip archive\n");
74 err
= unzOpenCurrentFile(zip
);
76 fprintf(stderr
,"ZipArchive: Could not open located file in zip archive\n");
80 unzGetCurrentFileInfo(zip
, &info
, NULL
, 0, NULL
, 0, NULL
, 0);
81 printf("ZipArchive: Length of extracted file: %lu\n", info
.uncompressed_size
);
82 zipbuf
->length
=info
.uncompressed_size
;
83 zipbuf
->data
=(uint8_t*)malloc(info
.uncompressed_size
);
84 if (zipbuf
->data
== NULL
) {
85 printf("ZipArchive: Error, cannot allocate tap buffer\n");
89 bool return_value
=true;
90 int bytes
=unzReadCurrentFile(zip
, zipbuf
->data
, info
.uncompressed_size
);
92 fprintf(stderr
, "ZipArchive: Error reading from file in zip archive\n");
97 unzCloseCurrentFile(zip
);
103 std::string
ZipArchive::tolower(std::string str
) {
104 std::transform(str
.begin(), str
.end(), str
.begin(), [](unsigned char c
){ return std::tolower(c
); });