7 static int gzipf(char*, int, int);
8 static int gzip(char*, long, int, Biobuf*);
9 static int crcread(void *fd, void *buf, int n);
10 static int gzwrite(void *bout, void *buf, int n);
24 fprint(2, "usage: gzip [-vcnD] [-1-9] [file ...]\n");
29 main(int argc, char *argv[])
50 case '1': case '2': case '3': case '4':
51 case '5': case '6': case '7': case '8': case '9':
59 crctab = mkcrctab(GZCRCPOLY);
62 sysfatal("deflateinit failed: %s", flateerr(ok));
65 Binit(&bout, 1, OWRITE);
66 ok = gzip(nil, mtime, 0, &bout);
70 for(i = 0; i < argc; i++)
71 ok &= gzipf(argv[i], !mtime, stdout);
73 exits(ok ? nil: "errors");
77 gzipf(char *file, int nomtime, int stdout)
80 char ofile[256], *f, *s;
83 ifd = open(file, OREAD);
85 fprint(2, "gzip: can't open %s: %r\n", file);
90 fprint(2, "gzip: can't stat %s: %r\n", file);
94 if(dir->mode & DMDIR){
95 fprint(2, "gzip: can't compress a directory\n");
103 strcpy(ofile, "<stdout>");
105 f = strrchr(file, '/');
111 if(s != nil && s != ofile && strcmp(s, ".tar") == 0){
113 snprint(ofile, sizeof(ofile), "%s.tgz", f);
115 snprint(ofile, sizeof(ofile), "%s.gz", f);
116 ofd = create(ofile, OWRITE, 0666);
118 fprint(2, "gzip: can't open %s: %r\n", ofile);
125 fprint(2, "compressing %s to %s\n", file, ofile);
127 Binit(&bout, ofd, OWRITE);
128 ok = gzip(file, nomtime ? 0 : dir->mtime, ifd, &bout);
129 if(!ok || Bflush(&bout) < 0){
130 fprint(2, "gzip: error writing %s: %r\n", ofile);
142 gzip(char *file, long mtime, int ifd, Biobuf *bout)
147 Bputc(bout, GZMAGIC1);
148 Bputc(bout, GZMAGIC2);
149 Bputc(bout, GZDEFLATE);
156 Bputc(bout, mtime>>8);
157 Bputc(bout, mtime>>16);
158 Bputc(bout, mtime>>24);
161 Bputc(bout, GZOSINFERNO);
164 Bwrite(bout, file, strlen(file)+1);
169 err = deflate(bout, gzwrite, (void*)ifd, crcread, level, debug);
171 fprint(2, "gzip: deflate failed: %s\n", flateerr(err));
177 Bputc(bout, crc>>16);
178 Bputc(bout, crc>>24);
181 Bputc(bout, totr>>8);
182 Bputc(bout, totr>>16);
183 Bputc(bout, totr>>24);
189 crcread(void *fd, void *buf, int n)
194 for(; !eof && n > 0; n -= m){
195 m = read((int)(uintptr)fd, (char*)buf+nr, n);
204 crc = blockcrc(crctab, crc, buf, nr);
210 gzwrite(void *bout, void *buf, int n)
212 if(n != Bwrite(bout, buf, n)){