-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.h
More file actions
71 lines (62 loc) · 2.38 KB
/
decode.h
File metadata and controls
71 lines (62 loc) · 2.38 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
#include "encode.h"
using namespace std;
/** Decode the header and generate the Huffman tree**/
void decode(const char* infilename) {
Node *root = new Node(0);// Create the root of the Huffman tree
// Open the input file in binary read mode
ifstream file(infilename, ios::binary);
if (!file) {
cerr << "Error opening input file" << endl;
return;
}
int uniqueCharacterCount = file.get();// Read the number of unique characters from the file
while(uniqueCharacterCount > 0) {
unsigned char ch = file.get(); // Character
unsigned char len = file.get(); // Length of Huffman code
Node* traverse = root;
// Construct the Huffman tree
while (len > 0) {
if (file.get() == '0') {
if (!traverse->left)
traverse->left = new Node(0); // Go to the left child
traverse = traverse->left;
} else {
if (!traverse->right)
traverse->right = new Node(0); // Go to the right child
traverse = traverse->right;
}
--len;
}
// character (1byte) + length(1byte) + huffmancode(n bytes where n is length of huffmancode)
traverse->character = ch; // Set the character in the node
--uniqueCharacterCount;
}
// Create the output file name and open it in binary write mode
string outfilename = string(infilename) + ".og";
ofstream optr(outfilename, ios::binary);
if (!optr) {
cerr << "Error opening output file" << endl;
file.close();
return;
}
// Decompress the encoded file
unsigned char buffer;
Node* traverse = root;
while (file.read(reinterpret_cast<char*>(&buffer), sizeof(buffer))) {
for (int counter = 7; counter >= 0; --counter) {
traverse = (buffer & (1 << counter)) ? traverse->right : traverse->left;
if (!traverse->left && !traverse->right) {
// Leaf node reached; output the character
optr.put(traverse->character);
traverse = root; // Go back to the root of the Huffman tree
}
}
}
// Close the files
file.close();
optr.close();
cout<<endl<<"Voila!! File has been successfully decoded and stored into "<<outfilename<<endl;
// Clean up memory
delete root, traverse;
return;
}