-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode.c
139 lines (137 loc) · 3.3 KB
/
decode.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "huffman.h"
char findCharacter(TABLE *head, unsigned int number, int size)
{
TABLE *cur = head;
while (cur != NULL)
{
if ((cur->num == number) && (cur->size == size))
{
return cur->character;
}
cur = cur->next;
}
return '\0';
}
void decode(TABLE **head, const char *filename)
{
FILE *fp = fopen(filename, "rb");
char fch = fgetc(fp);
char sch = fgetc(fp);
unsigned int val;
int number;
while (!(fch == '#' && sch == '#'))
{
TABLE *temp = getTableNode();
temp->character = fch;
sch = fgetc(fp);
val = sch - '0';
sch = fgetc(fp);
while (sch != ':')
{
val = (val * 10) + (sch - '0');
fch = sch;
sch = fgetc(fp);
}
temp->num = val;
sch = fgetc(fp);
number = sch - '0';
sch = fgetc(fp);
while (sch != ' ')
{
number = (number * 10) + (sch - '0');
sch = fgetc(fp);
}
temp->size = number;
sch = fgetc(fp);
fch = sch;
sch = fgetc(fp);
if (*head == NULL)
{
*head = temp;
}
else
{
temp->next = *head;
*head = temp;
}
}
sch = fgetc(fp);
unsigned char c1, c2, c0, c3;
c3 = fgetc(fp);
c0 = fgetc(fp);
c1 = fgetc(fp);
c2 = fgetc(fp);
unsigned int tempch = 0b0;
char mych;
int size = 0;
int overflow = 8;
char *hufffile = (char *)malloc(sizeof(char) * (strlen(filename) - 4));
strncpy(hufffile, filename, (strlen(filename) - 5));
hufffile[strlen(filename) - 5] = '\0';
FILE *noice = fopen(hufffile, "w+");
while (!(c0 == '#' && c1 == '#' && c2 == '#'))
{
while (overflow != 0)
{
if ((c3 & (1 << (overflow - 1))) == 0)
{
tempch = tempch << 1;
}
else
{
tempch = (tempch << 1) + 0b1;
}
size++;
overflow--;
if ((mych = findCharacter(*head, tempch, size)) != '\0')
{
fprintf(noice, "%c", mych);
tempch = 0b0;
size = 0;
}
}
overflow = 8;
c3 = c0;
c0 = c1;
c1 = c2;
c2 = fgetc(fp);
}
overflow = 8;
fseek(fp, -1, SEEK_END);
char asdch = fgetc(fp);
int gotch = (asdch - '0');
if(gotch == 0)
{
gotch = 8;
}
fseek(fp, -5, SEEK_END);
asdch = fgetc(fp);
while(gotch != 0)
{
if ((asdch & (1 << (overflow - 1))) == 0)
{
tempch = tempch << 1;
}
else
{
tempch = (tempch << 1) + 0b1;
}
overflow--;
gotch--;
size++;
if ((mych = findCharacter(*head, tempch, size)) != '\0')
{
fprintf(noice, "%c", mych);
tempch = 0b0;
size = 0;
}
}
fclose(fp);
fclose(noice);
freeTable(&(*head));
printf("Successfully Decoded\n");
exit(EXIT_SUCCESS);
}