usaa21/sk2a/compressor.c
Peter Petrek cfbcf91b0d try
2022-01-19 16:52:37 +01:00

82 lines
1.9 KiB
C

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compressor.h"
#define BUFSIZE 1024
int ByteRLEEncode(char* bufferIn, int size, char* bufferOut) {
int posIn = 0, count = 1, posOut = 0;
char byteCurrent, byteRLE = bufferIn[posIn++];
while (posIn != size) {
byteCurrent = bufferIn[posIn++];
if (byteCurrent == byteRLE) {
count++;
if (count == 256) {
bufferOut[posOut++] = byteRLE;
bufferOut[posOut++] = 255;
count = 1;
}
} else {
bufferOut[posOut++] = byteRLE;
bufferOut[posOut++] = count;
byteRLE = byteCurrent;
count = 1;
}
}
bufferOut[posOut++] = byteRLE;
bufferOut[posOut++] = count;
return posOut;
}
int mycompress(char* bufferIn, int size, char* bufferOut){
return ByteRLEEncode(bufferIn, size, bufferOut);;
}
void compress(FILE *infile, FILE *outfile){
char buffer[BUFSIZE];
memset(buffer,0,BUFSIZE);
while(1){
int insize = fread(buffer,sizeof(char),BUFSIZE,infile);
if (insize == 0){
if (feof(infile)){
// end of file
break;
}
assert(!ferror(infile));
}
char outbuf[BUFSIZE*2];
// Doplnte implementaciu kompresie.
int outsize = mycompress(buffer,insize,outbuf);
if (outsize > 0){
fwrite(outbuf,sizeof(char),outsize,outfile);
}
}
}
void decompress(FILE *infile, FILE *outfile){
unsigned char RLEMetadata[2];
char RLEData[255];
while (fread(RLEMetadata, 2, 1, infile)) {
printf("%c %d\n", RLEMetadata[0], RLEMetadata[1]);
for (int i = 0; i < RLEMetadata[1]; i++) {
RLEData[i] = RLEMetadata[0];
}
fwrite(RLEData, RLEMetadata[1], 1, outfile);
}
}