Richard’s Weblog

February 17, 2009

Perl, writing bytes to a file

Filed under: mood — Richard @ 1:30 am
Tags: ,

Here is a little script I wrote while learning Perl. It generates a binary file with exactly the specified size in bytes, kb, mb or gb. All bits are set to 1.

use File::stat;
use Switch;
$usageMessage = <<END;
Usage :
        perl fileGenerator [] 

                 :        Size of the file to generate, in bytes.
                 :        Name of the file to generate.
                 :        The unit of the file.
                                Possible values are k or K for kilo-bytes,
                                m or M for mega-bytes and g or G for giga-bytes.
                                If not specified, it will be interpreted
                                as "number of bytes".
END
die $usageMessage if @ARGV != 2 || $ARGV[0] !~ /\A[0-9]+[kKmMgG]?\Z/;
$ARGV[0] =~ /([0-9]+)([KkmMgG])/;
$size = $1;
$units = $2;
switch ($units) {
        case /[kK]/  { $numberOfBytes = $size*1024 }
        case /[mM]/  { $numberOfBytes = $size*1024*1024 }
        case /[gG]/  { $numberOfBytes = $size*1024*1024*1024 }
        else    :       { $numberOfBytes = $size }
}

open $file, '>', $ARGV[1] or die "Can't open file $ARGV[1]:$!";
vec($buffer, 0, 8) = 255;
print $file $buffer for (1..$numberOfBytes);
close($file);

Note that this is pretty slow since I write bytes one by one. I’ve not yet figured out how I could easily write more without losing precision in the size of the generated file. Suggestions are always welcome :)

Create a free website or blog at WordPress.com.