-
Notifications
You must be signed in to change notification settings - Fork 0
/
htable.c
113 lines (82 loc) · 1.97 KB
/
htable.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include "hufftools.h"
/* make pre declarations of functions so main recognizes them */
void decimalToHex(char lookuptable[][256]);
int main(int argc, char *argv[]) {
/* initializing variables and structures */
int *histogram;
int i;
int j;
char lookuptable[256][256];
char code[256];
int traversed;
int uniqchars = 0;
int inputFile = open(argv[1], O_RDONLY);
if (inputFile == -1) {
perror("Cannot open file");
exit(1);
}
traversed = 0;
i = 0;
j = 0;
histogram = (int* )construct_hist(inputFile);
close(inputFile);
struct LinkedList* list = createLinkedList();
/* insert Nodes that have at least Freq 1 into LinkedList sorted */
while (i < 256) {
if (histogram[i] > 0) {
uniqchars = uniqchars + 1;
struct Node* node = createNode(histogram[i],
(unsigned char)i);
insertsorted(list, node);
}
i = i + 1;
}
/* if there is only 1 char */
if (list->size == 1) {
printf("0x%02x: \n", (int)list->head->byte);
}
else {
struct Node* root = buildHuffTree(list);
/*clear lookuptable and array for storing the code*/
clearcodetable(code);
clearlookuptable(lookuptable);
/* traverses tree, stores code in lookuptable */
DFSAndBuildCode(root, lookuptable, traversed, code);
decimalToHex(lookuptable);
int inputfile = open(argv[1], O_RDONLY);
if (inputfile == -1) {
perror("Error Opening File");
exit(1);
}
/* temp structs to free all nodes in list */
struct Node* temp;
struct Node* temp2;
temp2 = list->head;
while (j < list->size) {
temp = temp2->next;
free(temp2);
temp2 = temp;
j = j + 1;
}
}
free(list);
free(histogram);
return 0;
}
void decimalToHex(char lookuptable[][256]) {
int i;
i = 0;
while (i < 256) {
/* %x turns to hex */
if (lookuptable[i][0] != '\0') {
printf("0x%02x: %s\n", i, lookuptable[i]);
}
i = i + 1;
}
}