This commit is contained in:
Bohdan Kapliuk 2025-01-12 17:32:53 +02:00
parent c12adb9efd
commit a2f98c8620

View File

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