6 static int bzipf(char*, int, int);
7 static int bzip(char*, long, int, Biobuf*);
18 fprint(2, "usage: bzip2 [-vcnD] [-1-9] [file ...]\n");
23 main(int argc, char **argv)
44 case '1': case '2': case '3': case '4':
45 case '5': case '6': case '7': case '8': case '9':
54 Binit(&bout, 1, OWRITE);
55 ok = bzip(nil, mtime, 0, &bout);
59 for(i = 0; i < argc; i++)
60 ok &= bzipf(argv[i], !mtime, stdout);
62 exits(ok ? nil: "errors");
66 bzipf(char *file, int nomtime, int stdout)
69 char ofile[128], *f, *s;
72 ifd = open(file, OREAD);
74 fprint(2, "bzip2: can't open %s: %r\n", file);
79 fprint(2, "bzip2: can't stat %s: %r\n", file);
83 if(dir->mode & DMDIR){
84 fprint(2, "bzip2: can't compress a directory\n");
92 strcpy(ofile, "<stdout>");
94 f = strrchr(file, '/');
100 if(s != nil && s != ofile && strcmp(s, ".tar") == 0){
102 snprint(ofile, sizeof(ofile), "%s.tbz", f);
104 snprint(ofile, sizeof(ofile), "%s.bz2", f);
105 ofd = create(ofile, OWRITE, 0666);
107 fprint(2, "bzip2: can't open %s: %r\n", ofile);
115 fprint(2, "compressing %s to %s\n", file, ofile);
117 Binit(&bout, ofd, OWRITE);
118 ok = bzip(file, nomtime ? 0 : dir->mtime, ifd, &bout);
119 if(!ok || Bflush(&bout) < 0){
120 fprint(2, "bzip2: error writing %s: %r\n", ofile);
132 bzip(char *file, long mtime, int ifd, Biobuf *bout)
134 int e, n, done, onemore;
143 memset(&strm, 0, sizeof strm);
144 BZ2_bzCompressInit(&strm, level, verbose, 0);
148 strm.next_out = obuf;
149 strm.avail_out = sizeof obuf;
152 Binit(&bin, ifd, OREAD);
155 * onemore is a crummy hack to go 'round the loop
156 * once after we finish, to flush the output buffer.
161 if(!done && strm.avail_in < sizeof buf) {
163 memmove(buf, strm.next_in, strm.avail_in);
165 n = Bread(&bin, buf+strm.avail_in, sizeof(buf)-strm.avail_in);
172 if(strm.avail_out < sizeof obuf) {
173 Bwrite(bout, obuf, sizeof(obuf)-strm.avail_out);
174 strm.next_out = obuf;
175 strm.avail_out = sizeof obuf;
180 } while((e=BZ2_bzCompress(&strm, done ? BZ_FINISH : BZ_RUN)) == BZ_RUN_OK || e == BZ_FINISH_OK || onemore--);
182 if(e != BZ_STREAM_END) {
183 fprint(2, "bzip2: compress failed\n");
187 if(BZ2_bzCompressEnd(&strm) != BZ_OK) {
188 fprint(2, "bzip2: compress end failed (can't happen)\n");