This commit is contained in:
Džubara 2025-01-19 20:52:36 +01:00
parent 6b809f03ea
commit 6796bfa7f1

View File

@ -143,19 +143,19 @@ int compress_1(const char* input_file_name, const char* output_file_name) {
unsigned char* data = read_file(input_file_name, &size);
if (!data) return -1;
// Build Huffman tree
HuffmanNode* root = build_huffman_tree(data, size);
if (!root) {
free(data);
return -1;
}
// Generate Huffman codes
char* codes[256] = {0};
char buffer[256];
generate_huffman_codes(root, codes, buffer, 0);
// Open output file
FILE* output_file = fopen(output_file_name, "wb");
if (!output_file) {
perror("Error opening output file");
@ -164,12 +164,17 @@ int compress_1(const char* input_file_name, const char* output_file_name) {
return -1;
}
// Compress data
unsigned char bit_buffer[1] = {0};
int bit_pos = 0;
for (size_t i = 0; i < size; i++) {
fputs(codes[data[i]], output_file);
write_bits(output_file, codes[data[i]], bit_buffer, &bit_pos);
}
// Flush remaining bits
if (bit_pos % 8 != 0) {
fwrite(bit_buffer, 1, 1, output_file);
}
fclose(output_file);
@ -187,6 +192,7 @@ int compress_1(const char* input_file_name, const char* output_file_name) {
}
int decompress_1(const char* input_file_name, const char* output_file_name) {
size_t size;
unsigned char* data = read_file(input_file_name, &size);