void main(int argc, char **argv) { int i, ok, stdout; char **oargv; oargv = argv; level = 6; stdout = 0; ARGBEGIN{ case 'D': debug++; break; case 'v': verbose++; break; case 'c': stdout++; break; case 'f': /* force */ break; case 'd': /* * gnu tar expects bzip2 -d to decompress * humor it. ugh. */ /* remove -d from command line - magic! */ if(strcmp(argv[0], "-d") == 0){ while(*argv++) *(argv-1) = *argv; }else memmove(_args-1, _args, strlen(_args)+1); exec("bunzip2", oargv); sysfatal("exec bunzip2 failed"); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = ARGC() - '0'; break; default: usage(); break; }ARGEND if(argc == 0){ Binit(&bout, 1, OWRITE); ok = bzip(nil, time(0), 0, &bout); Bterm(&bout); }else{ ok = 1; for(i = 0; i < argc; i++) ok &= bzipf(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 bzipf(char *file, int stdout) { Dir *dir; char ofile[128], *f, *s; int ifd, ofd, ok; ifd = open(file, OREAD); if(ifd < 0){ fprint(2, "bzip2: can't open %s: %r\n", file); return 0; } dir = dirfstat(ifd); if(dir == nil){ fprint(2, "bzip2: can't stat %s: %r\n", file); close(ifd); return 0; } if(dir->mode & DMDIR){ fprint(2, "bzip2: can't compress a directory\n"); close(ifd); free(dir); return 0; } if(stdout){ ofd = 1; strcpy(ofile, "<stdout>"); }else{ f = strrchr(file, '/'); if(f != nil) f++; else f = file; s = strrchr(f, '.'); if(s != nil && s != ofile && strcmp(s, ".tar") == 0){ *s = '\0'; snprint(ofile, sizeof(ofile), "%s.tbz", f); }else snprint(ofile, sizeof(ofile), "%s.bz2", f); ofd = create(ofile, OWRITE, 0666); if(ofd < 0){ fprint(2, "bzip2: can't open %s: %r\n", ofile); free(dir); close(ifd); return 0; } } if(verbose) fprint(2, "compressing %s to %s\n", file, ofile); Binit(&bout, ofd, OWRITE); ok = bzip(file, dir->mtime, ifd, &bout); if(!ok || Bflush(&bout) < 0){ fprint(2, "bzip2: error writing %s: %r\n", ofile); if(!stdout) remove(ofile); } Bterm(&bout); free(dir); close(ifd); close(ofd); return ok; }