Compress-Bzip2

 view release on metacpan or  search on metacpan

lib/Compress/Bzip2.pm  view on Meta::CPAN

  my %opts;
  return undef if !getopt( $opts, \%opts );
  # c compress or decompress to stdout
  # d decompress
  # z compress
  # f force
  # v verbose
  # k keep
  # s small
  # 123456789

  $opts{c} = 1 if $command eq 'bzcat';
  $opts{d} = 1 if $command eq 'bunzip2' || $command eq 'bzcat';
  $opts{z} = 1 if $command eq 'bzip2';

  my $read_from_stdin;
  my ( $in, $bzin );
  my ( $out, $bzout );

  if ( !@ARGV ) {
    $read_from_stdin = 1;
    $opts{c} = 1;
    if ( !open( $in, "<&STDIN" ) ) {
      die "Error: failed to input from STDIN: '$!'\n";
    }

    $bzin = bzopen( $in, "r" );
  }

  if ( $opts{c} ) {
    if ( !open( $out, ">&STDOUT" ) ) {
      die "Error: failed to output to STDOUT: '$!'\n";
    }

    $bzout = bzopen( $out, "w" );
  }

  if ( !$opts{d} && !$opts{z} ) {
    die "Error: neither compress nor decompress was indicated.\n";
  }

  my $doneflag = 0;
  while ( !$doneflag ) {
    my $infile;
    my $outfile;
    my @statbuf;

    if ( !$read_from_stdin ) {
      $infile = shift @ARGV;
      if ( ! -r $infile ) {
	print STDERR "Error: file $infile is not readable\n";
	next;
      }

      @statbuf = stat _;
      if ( !@statbuf ) {
	print STDERR "Error: failed to stat $infile: '$!'\n";
	next;
      }

      if ( !_check_stat( $infile, \@statbuf, $opts{f} ) ) {
	print STDERR "Error: file $infile stat check fails: $bzerrno\n";
	next;
      }
    }

    my $outfile_exists;
    if ( !$opts{c} ) {
      undef $out;
      if ( $opts{d} ) {
	$outfile = $infile . '.bz2';
      }
      elsif ( $opts{z} ) {
	$outfile = $infile =~ /\.bz2$/ ? substr($infile,0,-4) : $infile.'.out';
      }

      $outfile_exists = -e $outfile;
      if ( !_writefileopen( $out, $outfile, $opts{f} ) ) {
	print STDERR "Error: failed to open $outfile for write: '$!'\n";
	next;
      }
    }

    if ( !$read_from_stdin ) {
      undef $in;
      if ( !open( $in, $infile ) ) {
	print STDERR "Error: unable to open $infile: '$!'\n";
	unlink( $outfile ) if !$outfile_exists;
	next;
      }
    }

    if ( $opts{d} ) {
      $bzin = bzopen( $in, "r" ) if !$read_from_stdin;

      my $buf;
      my $notdone = 1;
      while ( $notdone ) {
	my $ln = bzread( $in, $buf, 1024 );
	if ( $ln > 0 ) {
	  syswrite( $out, $buf, $ln );
	}
	elsif ( $ln == 0 ) {
	  undef $notdone;
	}
	else {
	}
      }

      close($out);

      if ( !$read_from_stdin ) {
	bzclose($in);
	unlink( $infile ) if !$opts{k};
	_set_stat_from_snapshot( $outfile, \@statbuf );
      }
    }
    elsif ( $opts{z} ) {
      $bzout = bzopen( $out, "w" ) if !$opts{c};

      my $buf;



( run in 1.520 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )