This commit is contained in:
Bohdan Kapliuk 2025-01-12 17:34:34 +02:00
parent a2f98c8620
commit 7eb6729b57

View File

@ -59,33 +59,43 @@ int compress_1(const char* input_file_name, const char* output_file_name) {
return 0; return 0;
} }
int decompress_1(const char* input_file_name, const char* output_file_name) { int decompress_1(const char* input_file_name, const char* output_file_name) {
FILE* input_file = fopen(input_file_name, "rb"); size_t size;
if (!input_file) return -1; unsigned char* data;
if (read_file(input_file_name, &data, &size) != 0) return -1;
FILE* output_file = fopen(output_file_name, "wb"); unsigned char* decompressed = malloc(size * 255);
if (!output_file) { if (!decompressed) {
fclose(input_file); free(data);
return -1; return -1;
} }
unsigned char index, byte; size_t write_idx = 0;
while (fread(&index, 1, 1, input_file) == 1) { for (size_t i = 0; i < size;) {
if (fread(&byte, 1, 1, input_file) == 1) { unsigned char byte = data[i++];
for (int i = 0; i < index; i++) { size_t count = 0;
fwrite(&byte, 1, 1, output_file); while (i < size && isdigit(data[i])) {
count = count * 10 + (data[i++] - '0');
} }
} for (size_t j = 0; j < count; j++) {
else { if (write_idx >= size * 255) {
// Якщо ми не змогли прочитати байт, закриваємо файли та повертаємо помилку size_t new_size = write_idx * 2;
fclose(input_file); unsigned char* new_buffer = realloc(decompressed, new_size);
fclose(output_file); if (!new_buffer) {
free(decompressed);
free(data);
return -1; return -1;
} }
decompressed = new_buffer;
}
decompressed[write_idx++] = byte;
}
} }
fclose(input_file); int result = write_file(output_file_name, decompressed, write_idx);
fclose(output_file); free(data);
return 0; free(decompressed);
return result == 0 ? (int)write_idx : -1;
} }
// LZ78 // LZ78