-
Notifications
You must be signed in to change notification settings - Fork 0
/
rle_encode.c
54 lines (38 loc) · 1.02 KB
/
rle_encode.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_STRING_LENGTH 256
int main(int argc, char **argv) {
assert(argc == 2);
FILE *fpIn = NULL;
FILE *fpOut = NULL;
fpIn = fopen(argv[1], "rb");
char outputFile[MAX_STRING_LENGTH];
strcpy(outputFile, argv[1]);
strcat(outputFile, ".rle");
fpOut = fopen(outputFile, "wb");
unsigned char current = 0;
unsigned char previous = 0;
unsigned char counter = 0;
fread(&previous, sizeof(previous), 1, fpIn);
while(1 == fread(¤t, sizeof(current), 1, fpIn)) {
if(counter == 255) {
fwrite(&counter, sizeof(counter), 1, fpOut);
fwrite(&previous, sizeof(previous), 1, fpOut);
counter = 0;
} else if (current == previous) {
counter++;
} else {
fwrite(&counter, sizeof(counter), 1, fpOut);
fwrite(&previous, sizeof(previous), 1, fpOut);
counter = 0;
}
previous = current;
}
fwrite(&counter, sizeof(counter), 1, fpOut);
fwrite(¤t, sizeof(current), 1, fpOut);
fclose(fpIn);
fclose(fpOut);
return 0;
}