-
Notifications
You must be signed in to change notification settings - Fork 1
/
my-zip.c
66 lines (51 loc) · 1.52 KB
/
my-zip.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
#include <stdio.h>
#include <stdlib.h>
void my_zip(FILE *stream);
void write_stdout(int count, int tmp);
/* This programs take one or many files in and compress them into a single zip file */
int main(int argc, char *argv[]) {
FILE *file;
/* If there are no files, exit */
if (argc == 1) {
printf("my-zip: file1 [file2 ...]\n");
exit(1);
} else {
for (int i = 1; i < argc; i++) {
if ((file = fopen(argv[i], "r")) == NULL) {
fprintf(stderr, "Error: cannot open file '%s'\n", argv[i]);
exit(1);
}
my_zip(file);
fclose(file);
}
}
printf("\n");
return 0;
}
/* Helper function to write the compressed content to the standard output */
void write_stdout(int count, int tmp) {
char ch = tmp;
/* Format: 4-byte integer and single character */
fwrite(&count, 4, 1, stdout);
fwrite(&ch, 1, 1, stdout);
}
/* Function that compress file's contents with run-length encoding (RLE) */
void my_zip(FILE *stream) {
int ch;
int tmp;
int count = 1;
/* Reading first char in file */
tmp = fgetc(stream);
/* Reading the file char by char */
while ((ch = fgetc(stream)) != EOF) {
/* Counting sequential occurrences of chars */
if (ch == tmp) {
count++;
/* When char changes, send the results to write_stdout() */
} else {
write_stdout(count, tmp);
tmp = ch;
count = 1;
}
}
}