void main(int argc, char **argv) { int i, ok, stdout; stdout = 0; ARGBEGIN{ case 'D': debug++; break; case 'c': stdout++; break; case 'v': verbose++; break; default: usage(); }ARGEND if(argc == 0){ Binit(&bin, 0, OREAD); infile = "<stdin>"; ok = bunzip(1, "<stdout>", &bin); }else{ ok = 1; for(i = 0; i < argc; i++) ok &= bunzipf(argv[i], stdout); } exits(ok ? nil: "errors"); }
/* The main function */ int main(int argc, char *argv[]) { int errcode; volatile int last_error; char const *input, *const *inputs; /* Parsing command line */ bzip_prgname = basename(argv[0]); parse_cmdline(argc, argv); /* The exception handler */ last_error = 0; if ((errcode = setjmp(exception_handler)) != 0) { bs_close(&input_bs); bs_close(&output_bs); if (!main_runtime.tolerant) exit(errcode); last_error = errcode; } /* The main loop */ for (inputs = main_runtime.inputs; (input = *inputs++) != NULL; ) { bs_open_input(&input_bs, input); if (!main_runtime.output || !output_bs.fname) bs_open_output(&output_bs, main_runtime.output); if (IS_COMPRESS()) bzip(&input_bs, &output_bs); else bunzip(&input_bs, &output_bs); if (!main_runtime.output || !*inputs) bs_close_output(&output_bs); bs_close_input(&input_bs); } /* while */ exit(last_error); } /* main */
static int bunzipf(char *file, int stdout) { char ofile[64], *s; int ofd, ifd, ok; infile = file; ifd = open(file, OREAD); if(ifd < 0){ fprint(2, "bunzip2: can't open %s: %r\n", file); return 0; } Binit(&bin, ifd, OREAD); if(Bgetc(&bin) != 'B' || Bgetc(&bin) != 'Z' || Bgetc(&bin) != 'h'){ fprint(2, "bunzip2: %s is not a bzip2 file\n", file); Bterm(&bin); close(ifd); return 0; } Bungetc(&bin); Bungetc(&bin); Bungetc(&bin); if(stdout){ ofd = 1; strcpy(ofile, "<stdout>"); }else{ s = strrchr(file, '/'); if(s != nil) s++; else s = file; strecpy(ofile, ofile+sizeof ofile, s); s = strrchr(ofile, '.'); if(s != nil && s != ofile && strcmp(s, ".bz2") == 0) *s = '\0'; else if(s != nil && (strcmp(s, ".tbz") == 0 || strcmp(s, ".tbz2") == 0)) strcpy(s, ".tar"); else if(strcmp(file, ofile) == 0){ fprint(2, "bunzip2: can't overwrite %s\n", file); Bterm(&bin); close(ifd); return 0; } ofd = create(ofile, OWRITE, 0666); if(ofd < 0){ fprint(2, "bunzip2: can't create %s: %r\n", ofile); Bterm(&bin); close(ifd); return 0; } delfile = ofile; } ok = bunzip(ofd, ofile, &bin); Bterm(&bin); close(ifd); if(!ok){ fprint(2, "bunzip2: can't write %s: %r\n", ofile); if(delfile) remove(delfile); } delfile = nil; if(!stdout && ofd >= 0) close(ofd); return ok; }