This commit is contained in:
Džubara 2025-01-19 20:56:27 +01:00
parent ed11fb58e2
commit ca84283fa2
2 changed files with 25 additions and 4 deletions

View File

@ -137,6 +137,25 @@ int read_bit(FILE* file, unsigned char* buffer, int* bit_pos) {
return bit;
}
HuffmanNode* deserialize_tree(FILE* file) {
int marker = fgetc(file);
if (marker == EOF) return NULL;
if (marker == '1') {
// Leaf node: Read the symbol
HuffmanNode* node = (HuffmanNode*)malloc(sizeof(HuffmanNode));
node->symbol = fgetc(file);
node->left = node->right = NULL;
return node;
}
// Internal node: Create a new node and deserialize children
HuffmanNode* node = (HuffmanNode*)malloc(sizeof(HuffmanNode));
node->left = deserialize_tree(file);
node->right = deserialize_tree(file);
return node;
}
int compress_1(const char* input_file_name, const char* output_file_name) {
size_t size;
@ -207,16 +226,15 @@ int decompress_1(const char* input_file_name, const char* output_file_name) {
return -1;
}
// Reconstruct Huffman tree (you should deserialize it from the file)
// Placeholder: This assumes you rebuild the same tree during decompression
HuffmanNode* root = /* Deserialize tree here */;
HuffmanNode* root = deserialize_tree(input_file);
if (!root) {
fclose(input_file);
fclose(output_file);
return -1;
}
// Decompress data
unsigned char bit_buffer[1];
int bit_pos = 0;
HuffmanNode* current = root;
@ -242,6 +260,7 @@ int decompress_1(const char* input_file_name, const char* output_file_name) {
}
int compress_2(const char* input_file_name, const char* output_file_name) {
size_t size;
unsigned char* data = read_file(input_file_name, &size);

View File

@ -33,4 +33,6 @@ void generate_huffman_codes(HuffmanNode* root, char** codes, char* buffer, int d
void free_huffman_tree(HuffmanNode* root);
HuffmanNode* deserialize_tree(FILE* file);
#endif