-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.c
More file actions
68 lines (60 loc) · 1.17 KB
/
encode.c
File metadata and controls
68 lines (60 loc) · 1.17 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int infile = STDIN_FILENO, outfile = STDOUT_FILENO;
switch (argc) {
case 3:
outfile = open(argv[1], O_WRONLY | O_CREAT);
if (outfile == -1) {
fprintf(stderr, "could not open file %s: %s\n",
argv[1], strerror(errno));
return 1;
}
case 2:
infile = open(argv[2], O_RDONLY);
if (infile == -1) {
fprintf(stderr, "could not open file %s: %s\n",
argv[2], strerror(errno));
return 1;
}
break;
case 1:
break;
default:
fprintf(stderr, "incorrect number of arguments (max 2)\n");
return 2;
}
char c;
int mode = 0;
uint8_t cc = 0;
/* write header bytes */
write(outfile, "OW", 2);
/* compress */
while (read(infile, &c, 1) == 1) {
for (int i = 0; i < 8; i++) {
if (mode == (c & 1)) {
cc++;
if (cc == 255) {
write(outfile, &cc, 1);
cc = 0;
mode = !mode;
}
} else {
write(outfile, &cc, 1);
cc = 1;
mode = !mode;
}
c >>= 1;
}
}
/* cleanup */
if (infile != STDIN_FILENO)
close(infile);
if (outfile != STDOUT_FILENO)
close(outfile);
}