-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwunzip.c
51 lines (42 loc) · 1.27 KB
/
wunzip.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
#include <stdio.h>
#include <stdlib.h>
static int read_4_byte_binary(char *compressed_chunk) {
int current_partial_int = compressed_chunk[3];
for (int i=2; i >= 0; i--) {
current_partial_int = (current_partial_int << 8) | compressed_chunk[i];
}
return current_partial_int;
}
char *reverse_rle(char compressed_chunk[]) {
char character = compressed_chunk[4];
int character_count = read_4_byte_binary(compressed_chunk);
char *uncompressed_string;
if ((uncompressed_string = calloc(1, character_count + 1)) == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILURE);
};
for (int i=0; i < character_count; i++)
uncompressed_string[i] = character;
return uncompressed_string;
}
int main(int argc, char *argv[]) {
if (argc <= 1) {
printf("wunzip: file1 [file2 ...]\n");
exit(EXIT_FAILURE);
}
FILE *file;
char compressed_chunk[5];
for (int i=1; i < argc; i++) {
char *file_name = argv[i];
if ((file = fopen(file_name, "r")) == NULL) {
perror("wzip: cannot open file");
exit(EXIT_FAILURE);
}
while (fread(&compressed_chunk, 5, 1, file)) {
char *uncompressed_string = reverse_rle(compressed_chunk);
printf("%s", uncompressed_string);
free(uncompressed_string);
}
fclose(file);
}
}