-
Notifications
You must be signed in to change notification settings - Fork 1
/
my-unzip.c
87 lines (68 loc) · 2 KB
/
my-unzip.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
86
87
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void unzip(FILE *stream);
/*struct which has the "z" format (4 byte integer and 1 byte unsigned char)*/
typedef struct Zipchunk {
int n;
unsigned char c;
} Zipchunk;
int main(int argc, char **argv) {
FILE *file;
if (argc == 1) {
printf("my-unzip: file1 [file2 ...]\n");
exit(1);
} else {
for (int i = 1; i < argc; i++) {
/*https://stackoverflow.com/questions/5297248/how-to-compare-last-n-characters-of-a-string-to-another-string-in-c*/
/*Validate the filetype to be .z and not anything else*/
int len = strlen(argv[i]);
/*Filename cannot be less than 3 characters long f.ex: A.z*/
if (len < 3){
printf("Error: incorrect filetype!\n");
exit(1);
}
char *end = &argv[i][len-2];
/*compare last 2 characters */
if(strcmp(".z", end) != 0){
printf("Error: incorrect filetype!\n");
exit(1);
}
if ((file = fopen(argv[i], "rb")) == NULL) {
fprintf(stderr, "Error: cannot open file '%s'\n", argv[i]);
exit(1);
}
unzip(file);
fclose(file);
printf("\n");
}
}
return 0;
}
void unzip(FILE *stream){
/*Integers which hold fread return values for loop condition*/
int i_z, c_z;
/*Function reads one number/character pair at a time, until it has nothing to read.*/
while (1){
/* Allocate memory in which we read from file*/
Zipchunk *z = malloc(sizeof(Zipchunk));
/*Check failed allocation*/
if(z == NULL) {
fprintf(stderr, "ERROR: could not allocate memory\n");
exit (-1);
}
/*Read first the integer and then the character from file to zipchunk values*/
i_z = fread(&z->n, sizeof(z->n), 1 , stream);
c_z = fread(&z->c, sizeof(z->c), 1, stream);
/* If we get both values, we continue, else we are done!*/
if (i_z != 1 || c_z != 1) {
free(z);
break;
}
/*Write n amount of times letter c to the output stream*/
for(int i =0; i < z->n; i++) {
printf("%c",z->c);
}
free(z);
}
}