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)
46 * gnu tar expects bzip2 -d to decompress
49 /* remove -d from command line - magic! */
50 if(strcmp(argv[0], "-d") == 0){
54 memmove(_args-1, _args, strlen(_args)+1);
55 exec("bunzip2", oargv);
56 sysfatal("exec bunzip2 failed");
58 case '1': case '2': case '3': case '4':
59 case '5': case '6': case '7': case '8': case '9':
68 Binit(&bout, 1, OWRITE);
69 ok = bzip(nil, time(0), 0, &bout);
73 for(i = 0; i < argc; i++)
74 ok &= bzipf(argv[i], stdout);
76 exits(ok ? nil: "errors");
80 bzipf(char *file, int stdout)
83 char ofile[128], *f, *s;
86 ifd = open(file, OREAD);
88 fprint(2, "bzip2: can't open %s: %r\n", file);
93 fprint(2, "bzip2: can't stat %s: %r\n", file);
97 if(dir->mode & DMDIR){
98 fprint(2, "bzip2: can't compress a directory\n");
106 strcpy(ofile, "<stdout>");
108 f = strrchr(file, '/');
114 if(s != nil && s != ofile && strcmp(s, ".tar") == 0){
116 snprint(ofile, sizeof(ofile), "%s.tbz", f);
118 snprint(ofile, sizeof(ofile), "%s.bz2", f);
119 ofd = create(ofile, OWRITE, 0666);
121 fprint(2, "bzip2: can't open %s: %r\n", ofile);
129 fprint(2, "compressing %s to %s\n", file, ofile);
131 Binit(&bout, ofd, OWRITE);
132 ok = bzip(file, dir->mtime, ifd, &bout);
133 if(!ok || Bflush(&bout) < 0){
134 fprint(2, "bzip2: error writing %s: %r\n", ofile);
146 bzip(char *file, long mtime, int ifd, Biobuf *bout)
148 int e, n, done, onemore;
157 memset(&strm, 0, sizeof strm);
158 BZ2_bzCompressInit(&strm, level, verbose, 0);
162 strm.next_out = obuf;
163 strm.avail_out = sizeof obuf;
166 Binit(&bin, ifd, OREAD);
169 * onemore is a crummy hack to go 'round the loop
170 * once after we finish, to flush the output buffer.
175 if(!done && strm.avail_in < sizeof buf) {
177 memmove(buf, strm.next_in, strm.avail_in);
179 n = Bread(&bin, buf+strm.avail_in, sizeof(buf)-strm.avail_in);
186 if(strm.avail_out < sizeof obuf) {
187 Bwrite(bout, obuf, sizeof(obuf)-strm.avail_out);
188 strm.next_out = obuf;
189 strm.avail_out = sizeof obuf;
194 } while((e=BZ2_bzCompress(&strm, done ? BZ_FINISH : BZ_RUN)) == BZ_RUN_OK || e == BZ_FINISH_OK || onemore--);
196 if(e != BZ_STREAM_END) {
197 fprint(2, "bzip2: compress failed\n");
201 if(BZ2_bzCompressEnd(&strm) != BZ_OK) {
202 fprint(2, "bzip2: compress end failed (can't happen)\n");