6 static int bzipf(char*, int);
7 static int bzip(char*, long, int, Biobuf*);
18 fprint(2, "usage: bzip2 [-vcD] [-1-9] [file ...]\n");
23 main(int argc, char **argv)
39 case '1': case '2': case '3': case '4':
40 case '5': case '6': case '7': case '8': case '9':
49 Binit(&bout, 1, OWRITE);
50 ok = bzip(nil, time(0), 0, &bout);
54 for(i = 0; i < argc; i++)
55 ok &= bzipf(argv[i], stdout);
57 exits(ok ? nil: "errors");
61 bzipf(char *file, int stdout)
64 char ofile[128], *f, *s;
67 ifd = open(file, OREAD);
69 fprint(2, "bzip2: can't open %s: %r\n", file);
74 fprint(2, "bzip2: can't stat %s: %r\n", file);
78 if(dir->mode & DMDIR){
79 fprint(2, "bzip2: can't compress a directory\n");
87 strcpy(ofile, "<stdout>");
89 f = strrchr(file, '/');
95 if(s != nil && s != ofile && strcmp(s, ".tar") == 0){
97 snprint(ofile, sizeof(ofile), "%s.tbz", f);
99 snprint(ofile, sizeof(ofile), "%s.bz2", f);
100 ofd = create(ofile, OWRITE, 0666);
102 fprint(2, "bzip2: can't open %s: %r\n", ofile);
110 fprint(2, "compressing %s to %s\n", file, ofile);
112 Binit(&bout, ofd, OWRITE);
113 ok = bzip(file, dir->mtime, ifd, &bout);
114 if(!ok || Bflush(&bout) < 0){
115 fprint(2, "bzip2: error writing %s: %r\n", ofile);
127 bzip(char *file, long mtime, int ifd, Biobuf *bout)
129 int e, n, done, onemore;
138 memset(&strm, 0, sizeof strm);
139 BZ2_bzCompressInit(&strm, level, verbose, 0);
143 strm.next_out = obuf;
144 strm.avail_out = sizeof obuf;
147 Binit(&bin, ifd, OREAD);
150 * onemore is a crummy hack to go 'round the loop
151 * once after we finish, to flush the output buffer.
156 if(!done && strm.avail_in < sizeof buf) {
158 memmove(buf, strm.next_in, strm.avail_in);
160 n = Bread(&bin, buf+strm.avail_in, sizeof(buf)-strm.avail_in);
167 if(strm.avail_out < sizeof obuf) {
168 Bwrite(bout, obuf, sizeof(obuf)-strm.avail_out);
169 strm.next_out = obuf;
170 strm.avail_out = sizeof obuf;
175 } while((e=BZ2_bzCompress(&strm, done ? BZ_FINISH : BZ_RUN)) == BZ_RUN_OK || e == BZ_FINISH_OK || onemore--);
177 if(e != BZ_STREAM_END) {
178 fprint(2, "bzip2: compress failed\n");
182 if(BZ2_bzCompressEnd(&strm) != BZ_OK) {
183 fprint(2, "bzip2: compress end failed (can't happen)\n");