-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
83 lines (67 loc) · 2.48 KB
/
main.cpp
File metadata and controls
83 lines (67 loc) · 2.48 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
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <ctime>
#include "Huffman.h"
using namespace std;
// Simple function to calculate file size
long long filesize(const string& filename) {
ifstream in(filename, ios::ate | ios::binary);
if(!in) return -1;
return in.tellg();
}
// Simple frequency map builder
unordered_map<char,int> buildFrequencyMap(const string& filename) {
unordered_map<char,int> freq;
ifstream file(filename, ios::binary);
if(!file.is_open()) {
cerr << "Error opening input file: " << filename << endl;
return freq;
}
char ch;
while(file.get(ch)) freq[ch]++;
file.close();
return freq;
}
int main() {
string inputFile = "input.txt";
string compressedFile = "compressed.huff";
string decompressedFile = "decompressed.txt";
cout << "Enter mode ('compress' or 'decompress'): ";
string mode;
cin >> mode;
Huffman huff;
if(mode == "compress") {
if(filesize(inputFile) <= 0) {
cerr << "Input file missing or empty!" << endl;
return 1;
}
cout << "Building frequency map..." << endl;
auto freqMap = buildFrequencyMap(inputFile);
cout << "Building Huffman tree..." << endl;
huff.huffer(freqMap);
cout << "Compressing file..." << endl;
clock_t start = clock();
huff.compressTofile(inputFile, compressedFile);
cout << "Compression done in " << (1.0*(clock()-start)/CLOCKS_PER_SEC) << " sec" << endl;
cout << "Input Size: " << filesize(inputFile) << " bytes" << endl;
cout << "Compressed Size: " << filesize(compressedFile) << " bytes" << endl;
cout << "Compression Ratio: "
<< (1.0 * filesize(compressedFile) / filesize(inputFile)) << endl;
} else if(mode == "decompress") {
if(filesize(compressedFile) <= 0) {
cerr << "Compressed file missing or empty!" << endl;
return 1;
}
cout << "Decompressing file..." << endl;
clock_t start = clock();
huff.deHuffer(compressedFile, decompressedFile);
cout << "Decompression done in " << (1.0*(clock()-start)/CLOCKS_PER_SEC) << " sec" << endl;
cout << "Compressed Size: " << filesize(compressedFile) << " bytes" << endl;
cout << "Decompressed Size: " << filesize(decompressedFile) << " bytes" << endl;
} else {
cerr << "Invalid mode! Use 'compress' or 'decompress'." << endl;
return 1;
}
return 0;
}