All pastes #825162 Raw Edit

Mine

public text v1 · immutable
#825162 ·published 2007-12-20 11:27 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
void compress(const char *inFilename, const char *outFilename)
{
    static char s[1024];
    unsigned char current, prev, compressed[3]="\e  ";
    int fd1, fd2, reps;

    if ((fd1 = open(inFilename, O_RDONLY, S_IREAD)) < 0)
    {
        sprintf(s, "\nCannot open file to compress: %s. ", inFilename);
        perror(s);
        getchar();
        exit(1);
    }
    if ((fd2 = open(outFilename, O_CREAT | O_WRONLY | O_TRUNC, S_IREAD | S_IWRITE)) < 0)
    {
        sprintf(s, "\nCannot create compressed file:%s. ", outFilename);
        perror(s);
        getchar();
        exit(1);
    }
    read(fd1, &prev, 1);
    reps = 1;
    while (read(fd1, &current, 1))
    {
        if (prev == current && reps < 255) reps++; // same char
        if (reps > 1 && reps <=3 && prev != current)
        {
            while (reps--)
            {
                if (write(fd2, &prev, 1) < 1)
                {
                    perror("Short write. ");
                    getchar();
                    exit(2);
                }
            }
            reps = 1;
        }
        else if ((reps > 3 && prev != current) || reps >= 255)
        {
            // more than 3 repetitions
            compressed[1] = prev;
            compressed[2] = (char)reps - 1;
            if (write(fd2, compressed, sizeof(compressed)) < sizeof(compressed))
            {
                perror("Short write. ");
                getchar();
                exit(2);
            }
            reps = 1;
        }
        else if (prev == '\e')
        {
            compressed[1] = prev;
            compressed[2] = 0;
            if (write(fd2, compressed, sizeof(compressed)) < sizeof(compressed))
            {
                perror("Short write. ");
                getchar();
                exit(2);
            }
        }
        else if (prev != current)
        {
            if (write(fd2, &prev, 1) < 1)
            {
                perror("Short write. ");
                getchar();
                exit(2);
            }
        }
        prev = current;
    }
    close(fd1);
    close(fd2);
}
void uncompress(char *inFilename)
{
    static char s[1024];
    unsigned char current, buf[2];
    int fd1;

    if ((fd1 = open(inFilename, O_RDONLY, S_IREAD)) < 0)
    {
        sprintf(s, "\nCannot open file to uncompress: %s. ", inFilename);
        perror(s);
        getchar();
        exit(1);
    }
    while (read(fd1, &current, 1))
    {
        if (current == '\33')
        {
            read(fd1, buf, sizeof(buf));
            while (buf[1]--) putchar(buf[0]);
        }
        else
            putchar(current);
    }
    close(fd1);
}


int main()
{
    compress("p106.txt", "rez.out");
    uncompress("rez.out");
    return 0;
}