-
Notifications
You must be signed in to change notification settings - Fork 66
/
shoco-bin.c
85 lines (71 loc) · 1.92 KB
/
shoco-bin.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "shoco.h"
static const char USAGE[] = "compresses or decompresses your (presumably short) data.\n"
"usage: shoco {c(ompress),d(ecompress)} <file-to-(de)compress> <output-filename>\n";
typedef enum {
JOB_COMPRESS,
JOB_DECOMPRESS,
} Job;
#define MAX_STACK_ALLOCATION_SIZE 65536
int main(int argc, char **argv) {
Job job;
unsigned long in_size;
char *in_buffer;
char *out_buffer;
FILE *fin;
FILE *fout;
int len;
if (argc < 4) {
puts(USAGE);
return 1;
}
if (argv[1][0] == 'c')
job = JOB_COMPRESS;
else if (argv[1][0] == 'd')
job = JOB_DECOMPRESS;
else {
puts(USAGE);
return 1;
}
char *infile = argv[2];
char *outfile = argv[3];
fin = fopen (infile, "rb" );
if (fin == NULL) {
fputs("Something went wrong opening the file. Does it even exist?", stderr);
exit(1);
}
// obtain file size:
fseek(fin, 0, SEEK_END);
in_size = ftell(fin);
rewind(fin);
if (in_size > MAX_STACK_ALLOCATION_SIZE) {
in_buffer = (char *)malloc(sizeof(char) * in_size);
out_buffer = (char *)malloc(sizeof(char) * in_size * 4);
if ((in_buffer == NULL) || (out_buffer == NULL)) {
fputs("Memory error. This really shouldn't happen.", stderr);
exit(2);
}
} else {
in_buffer = (char *)alloca(sizeof(char) * in_size);
out_buffer = (char *)alloca(sizeof(char) * in_size * 4);
}
if (fread(in_buffer, sizeof(char), in_size, fin) != in_size) {
fputs("Error reading the input file.", stderr);
exit(3);
}
fclose(fin);
if (job == JOB_COMPRESS)
len = shoco_compress(in_buffer, in_size, out_buffer, in_size * 4);
else
len = shoco_decompress(in_buffer, in_size, out_buffer, in_size * 4);
fout = fopen(outfile, "wb");
fwrite(out_buffer , sizeof(char), len, fout);
fclose(fout);
if (in_size > MAX_STACK_ALLOCATION_SIZE) {
free(in_buffer);
free(out_buffer);
}
return 0;
}