开发者

Zipping files by group size in a directory

I have 2 directories that I have to open and zip all files in there. My issue is that my zip files can only be 5MB each, and these files are big. I have to some how group these files by size before zipping them. I would like to do this using Perl's Archive::Zip module. I have some code but I was wondering if someone here would know a way to do this, well here is the code:

#!/perl/bin/perl -w
use strict;
use warnings;

use Archive::Zip qw/AZ_OK/;
use File::Temp qw/tempfile/;

use constant MB => 1024 * 1024;

#my @dir = '/dir1 dir2/';
my $dir = qw( dir1/);

my @files = do {
 opendir my $fd, "$dir" or die $! or die $!;
 grep -f, map  "$dir$_", readdir $fd;
};

my $zip = Archive::Zip->new;
my $total;
my $limi开发者_运维问答t = 5*MB;



foreach my $file (@files) {

 my $temp = Archive::Zip->new;

 my $member = $temp->addFile($file);
 next unless $member->compressedSize;

 my $fh = tempfile();
 $temp->writeToFileHandle($fh) == AZ_OK or die $!;

 $zip->addMember($member);
 $total += $member->compressedSize;
 die "$total bytes exceeds archive size limit" if $total > $limit;

}

print "Total archive size: $total bytes\n\n";

$zip->writeToFileNamed('zipped.zip') == AZ_OK or die $!;

Thanks!


IMHO you are solving the wrong problem. If you need to zip the files into 5M chunks, why not zip them all together and then split into 5M chunks?

You can do the splitting internally to perl (a good example is here); or for less portable solution use a system command split (available on Unix/Linux; there's a DOS port as well)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜