Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #define MAX_REP 255
- void rle_compress(char *infile, char *outfile) {
- FILE *inf = fopen(infile, "rb");
- FILE *outf = fopen(outfile, "wb");
- char prevChar = 0, currChar = 0;
- bool first = true, rep = false;
- unsigned char repCount = 0;
- while (fread(&currChar, sizeof(char), 1, inf)) {
- if (!rep)
- fwrite(&currChar, sizeof(char), 1, outf);
- if (first) {
- first = false;
- } else {
- if (prevChar == currChar) {
- if (!rep) {
- rep = true;
- repCount = 2;
- } else {
- repCount++;
- if (repCount == MAX_REP) {
- fwrite(&repCount, sizeof(unsigned char), 1, outf);
- rep = false;
- repCount = 0;
- first = true;
- }
- }
- } else {
- if (rep) {
- fwrite(&repCount, sizeof(unsigned char), 1, outf);
- rep = false;
- repCount = 0;
- fwrite(&currChar, sizeof(char), 1, outf);
- }
- }
- }
- prevChar = currChar;
- }
- rep && fwrite(&repCount, sizeof(unsigned char), 1, outf);
- fclose(outf);
- fclose(inf);
- }
- void rle_decompress(char *infile, char *outfile)
- {
- FILE *inf = fopen(infile, "rb");
- FILE *outf = fopen(outfile, "wb");
- unsigned char prevChar = 0, currChar = 0;
- bool rep = false, passOne = false;
- size_t rd;
- while (!feof(inf))
- {
- rd = fread(&currChar, sizeof(currChar), 1, inf);
- if (rd == 0)
- break;
- if (rep)
- {
- for (int i = 0; i < currChar - 2; i++)
- fwrite(&prevChar, sizeof(prevChar), 1, outf);
- rep = false;
- passOne = true;
- }
- else
- {
- fwrite(&currChar, sizeof(currChar), 1, outf);
- if (passOne)
- passOne = false;
- else if (currChar == prevChar)
- rep = true;
- }
- prevChar = currChar;
- }
- fclose(outf);
- fclose(inf);
- }
- int main(int argc, char *argv[])
- {
- if (argc != 2)
- {
- printf("RLE Compressor by Gorodilova Love\nUsage:\n");
- printf("\trle.exe <c|d>\nwhere\n");
- printf("\t<c|d> - c - for compression, d - for decompression\n");
- return 0;
- }
- if ((argv[1][0] == 'c') || (argv[1][0] == 'C'))
- rle_compress("input.txt", "output.txt");
- else if ((argv[1][0] == 'd') || (argv[1][0] == 'D'))
- rle_decompress("input.txt", "output.txt");
- return 0;
- }
Add Comment
Please, Sign In to add comment