-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunpacker.cpp
More file actions
91 lines (68 loc) · 2.16 KB
/
Copy pathunpacker.cpp
File metadata and controls
91 lines (68 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "unpacker.h"
#include <fstream>
#include <iostream>
#include <filesystem>
#include <string>
#include "code_table.h"
#include "code_input_stream.h"
#include "code.h"
using namespace std;
unsigned int readInt(ifstream &input);
void unpack(const string &file) {
ifstream input(file, ios::in | ios::binary);
while (input.peek() != EOF) {
unsigned int fileNameLength = readInt(input);
char *fileName = new char[fileNameLength + 1]; // +1 for '\0'
input.read(fileName, fileNameLength);
fileName[fileNameLength] = '\0';
cout << "Decompressing file " << fileName << "... ";
cout.flush();
if (filesystem::exists(fileName)) {
cerr << endl
<< "File is not empty. Recreating it... ";
cerr.flush();
filesystem::remove(fileName);
}
CodeInputStream codeStream(&input);
ofstream output(fileName, ios::out | ios::binary);
decompress(codeStream, output);
output.close();
cout << "Done." << endl;
delete[] fileName;
}
input.close();
}
unsigned int readInt(ifstream &input) {
size_t size = sizeof(int);
byte *bytes = new byte[size];
input.read(reinterpret_cast<char *>(bytes), size);
unsigned int value = 0;
for (int i = 0; i < size; ++i) {
value = (value << 8u) + static_cast<unsigned char>(bytes[i]);
}
delete[] bytes;
return value;
}
void decompress(CodeInputStream &input, ofstream &output) {
CodeTable table;
Code oldCode, code;
string oldValue, value;
input >> code;
output << table.getValue(code);
oldCode = code;
while (input >> code) {
if (table.contains(code)) {
value = table.getValue(code);
output.write(value.c_str(), value.length());
oldValue = table.getValue(oldCode);
table.putValue(oldValue + value[0]);
oldCode = code;
} else {
oldValue = table.getValue(oldCode);
value = oldValue + oldValue[0];
output.write(value.c_str(), value.length());
table.putValue(value);
oldCode = code;
}
}
}