Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jibsen
Created February 6, 2015 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jibsen/214d1abfaf2d78515e6b to your computer and use it in GitHub Desktop.
Save jibsen/214d1abfaf2d78515e6b to your computer and use it in GitHub Desktop.
Tsukiyama RLE compressor
// Tsukiyama RLE compressor
// Usage: tsukiyama c|d input output
// Originally by Matt Mahoney, adapted for Tsukiyama. Public domain.
#include <stdio.h>
int main(int argc, char** argv) {
// Check args
if (argc!=4)
return printf("To compress|decompress: tsukiyama c|d input output\n"), 1;
// Open files
FILE* in=fopen(argv[2], "rb");
if (!in) return perror(argv[2]), 1;
FILE* out=fopen(argv[3], "wb");
if (!out) return perror(argv[3]), 1;
int c, c1=-1; // current and last char
int run=0; // current run length
// Compress
if (argv[1][0]=='c') {
// RLE encode
do {
c=getc(in);
if (c==c1) {
if (++run==256) { putc(c1, out); putc(255, out); run=0; }
}
else {
if (run>0) { putc(c1, out); putc(run-1, out); run=0; }
if (c!=EOF) putc(c, out);
}
c1=c;
} while (c!=EOF);
}
// Decompress
else if (argv[1][0]=='d') {
// Decode
c1=-1;
while ((c=getc(in))!=EOF) {
if (c==c1) {
if ((run=getc(in))==EOF) return 1;
for (++run; run>0; --run) putc(c, out);
}
else {
putc(c, out);
}
c1=c;
}
}
// Print result
printf("TRLE %lu -> %lu\n", ftell(in), ftell(out));
fclose(in);
fclose(out);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment