You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

98 lines
2.3 KiB

#include "assert.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "unistd.h"
//LZ77 decompression (No Error checking)
void wocky(char *buff, int buff_len, FILE *f) {
int table_max = 32, table_len = 1;
char **table = (char**) calloc(table_max, sizeof(char*));
table[0] = "";
int buff_index = 0, len = 0, bound = 1;
while(buff_index < buff_len) {
char *bin_int = (char*) calloc(len+1, sizeof(char));
int bin_index = 0;
for (int i = 0; i < len; ++i) {
bin_int[i] = buff[buff_index+i];
bin_index += (bin_int[i] - '0') << (len-1-i);
}
char *s = NULL;
if (table[bin_index] != NULL) {
s = (char*) calloc(strlen(table[bin_index])+2, sizeof(char));
//Copy contents to s
strcat(s, table[bin_index]);
}
else {
s = (char*) calloc(2, sizeof(char));
}
buff_index += len;
//Make sure to account for end to file edge case
if (buff_index < buff_len)
s[strlen(s)] = buff[buff_index++];
//Make sure table isn't full
if (table_len == table_max) {
table_max <<= 1;
table = (char**) realloc(table, table_max*sizeof(char*));
memset(table+table_len, 0, table_len);
}
//Increase upper bound
if (table_len == bound) {
bound <<= 1;
++len;
}
table[table_len++] = s;
fprintf(f, "%s", s);
fflush(f);
free(bin_int);
}
}
int main(int argc, char **argv) {
assert(argc == 3);
struct stat sbuf = {};
if (stat(argv[1], &sbuf) != 0) {
fprintf(stderr, "Error finding file\n");
return -1;
}
//Assume we can read the file
char *inbuff = (char*) malloc((sbuf.st_size+1) * sizeof(char));
char *outbuff = (char*) malloc((sbuf.st_size+1) * sizeof(char));
int out_len = 0;
FILE *f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "Error opening input file\n");
return -1;
}
if (fread(inbuff, sizeof(char), sbuf.st_size, f) != sbuf.st_size) {
fclose(f);
fprintf(stderr, "Error reading file\n");
return -1;
}
//Close file when done reading
fclose(f);
f = fopen(argv[2], "w");
if (f == NULL) {
fprintf(stderr, "Error opening output file\n");
return -1;
}
//Write contents of jabber back out
wocky(inbuff, sbuf.st_size, f);
fclose(f);
return 0;
}