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".
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);

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 :)


1 Comment »

  1. Your specifics concerning the matter happen to be unique.
    I’m guessing you tend not to mind in case I publish a bit of
    this great article with my favorite visitors.

    Comment by — March 1, 2018 @ 8:22 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: