Skip to content

Commit a57bea8

Browse files
committed
Add ZipReader class
1 parent 0209ae0 commit a57bea8

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed

src/internal/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,6 @@ target_sources(scratchcpp
44
scratch3reader.cpp
55
scratch3reader.h
66
reader_common.h
7+
zipreader.cpp
8+
zipreader.h
79
)

src/internal/zipreader.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
#include "zipreader.h"
4+
5+
using namespace libscratchcpp;
6+
7+
ZipReader::ZipReader(const std::string &fileName) :
8+
m_fileName(fileName)
9+
{
10+
}
11+
12+
ZipReader::ZipReader(const char *fileName) :
13+
ZipReader(std::string(fileName))
14+
{
15+
}
16+
17+
ZipReader::~ZipReader()
18+
{
19+
close();
20+
}
21+
22+
bool ZipReader::open()
23+
{
24+
m_zip = zip_open(m_fileName.c_str(), 0, 'r');
25+
return m_zip;
26+
}
27+
28+
void ZipReader::close()
29+
{
30+
if (m_zip)
31+
zip_close(m_zip);
32+
33+
m_zip = nullptr;
34+
}
35+
36+
size_t ZipReader::readFile(const std::string &fileName, void **buf)
37+
{
38+
if (!m_zip) {
39+
buf = nullptr;
40+
return 0;
41+
}
42+
43+
size_t bufsize = 0;
44+
zip_entry_read(m_zip, buf, &bufsize);
45+
46+
return bufsize;
47+
}
48+
49+
std::string ZipReader::readFileToString(const std::string &fileName)
50+
{
51+
void *buf = nullptr;
52+
size_t bufsize = readFile(fileName, &buf);
53+
54+
if (buf) {
55+
std::string ret(reinterpret_cast<char *>(buf), bufsize);
56+
free(buf);
57+
58+
return ret;
59+
}
60+
61+
return "";
62+
}

src/internal/zipreader.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
#pragma once
4+
5+
#include <string>
6+
#include <zip.h>
7+
8+
namespace libscratchcpp
9+
{
10+
11+
class ZipReader
12+
{
13+
public:
14+
ZipReader(const std::string &fileName);
15+
ZipReader(const char *fileName);
16+
ZipReader(const ZipReader &) = delete;
17+
~ZipReader();
18+
19+
bool open();
20+
void close();
21+
22+
size_t readFile(const std::string &fileName, void **buf);
23+
std::string readFileToString(const std::string &fileName);
24+
25+
private:
26+
std::string m_fileName;
27+
struct zip_t *m_zip = nullptr;
28+
};
29+
30+
} // namespace libscratchcpp

0 commit comments

Comments
 (0)