Update sk1/compressor.c

This commit is contained in:
Yurii Yakovenko 2025-01-29 20:41:47 +00:00
parent 8085a6894a
commit 141ae3e784

View File

@ -2,7 +2,7 @@
#include <stdlib.h>
#define WSIZE 250
#define BSIZE 50
///----------------------------LZ77-------------
typedef struct {
unsigned char pos;
unsigned char n;
@ -134,6 +134,110 @@ int decompress_1(const char* input_file, const char* output_file)
fclose(input);
fclose(output);
return compr_size;
}//-------------------------------------RLE--------------------
int compress_2(const char* input_file, const char* output_file) {
int ch, nchar;
unsigned char count = 1;
int compr_size = 0;
FILE* in = fopen(input_file, "rb");
FILE* out = fopen(output_file, "wb");
if (!in || !out) {
if (in) fclose(in);
if (out) fclose(out);
return -1;
}
ch = fgetc(in);
while (ch != EOF) {
nchar = fgetc(in);
if (nchar == ch) {
count++;
if (count == 127) {
fputc(count, out);
fputc(ch, out);
compr_size += 2;
count = 1;
ch = fgetc(in);
}
}
else {
if (count > 1) {
fputc(count, out);
fputc(ch, out);
compr_size += 2;
}
else {
int rizn = 1;
char buffer[127];
buffer[0] = ch;
while (nchar != EOF && nchar != ch && rizn < 127) {
buffer[rizn] = nchar;
rizn++;
ch = nchar;
nchar = fgetc(in);
}
fputc(0x80 | rizn, out);
compr_size += 1;
for (int i = 0; i < rizn; i++) {
fputc(buffer[i], out);
compr_size += 1;
}
}
count = 1;
ch = nchar;
}
}
fclose(in);
fclose(out);
return compr_size;
}
int decompress_2(const char* input_file, const char* output_file) {
int byte;
int compr_size = 0;
FILE* in = fopen(input_file, "rb");
FILE* out = fopen(output_file, "wb");
if (!in || !out) {
if (in) fclose(in);
if (out) fclose(out);
return -1;
}
while ((byte = fgetc(in)) != EOF) {
if (byte & 0x80) {
int count = byte & 0x7F;
for (int i = 0; i < count; i++) {
int ch = fgetc(in);
if (ch == EOF) break;
fputc(ch, out);
compr_size += 1;
}
}
else {
int count = byte;
int ch = fgetc(in);
for (int i = 0; i < count; i++) {
fputc(ch, out);
compr_size += 1;
}
}
}
fclose(in);
fclose(out);
return compr_size;
}