0

I have a line like dd if=/dev/zero of=myImg.img bs=1KB count=1024k , which I have to do several times in my script. Therefore i wanted to integrate this line in my perl script, not by doing a system('...'); call, but by creating a funktion. Is there a good way to do so?

I've tried it with MakeMaker, but i didn't find a proper way to set my filelength/offset the right way, or anything similar to the -o -l from fallocate. And of course, the obvious way open(FH,">/myFolder/MyImg.img"); didn't work, either.

yoko
  • 516
  • 1
  • 3
  • 18

2 Answers2

2

fallocate(1) has the advantage of being much faster than the pure-Perl way of writing out a gigabyte of zero bytes. It uses a Linux-specific syscall that does have a POSIX equivalent but unfortunately that's not implemented by the POSIX module. If you can use sparse files (the only application I can think of right now that really doesn't like them is using the files as swap space), the easiest way is to call truncate($fh, $size). But of course you do need to open the file for writing first -- why didn't this work?

mbethke
  • 935
  • 8
  • 19
1

Your question amounts to the following:

How can I create a 1,000 MiB file of NUL bytes in Perl?

You could use the following:

open(my $fh, '>', $qfn)
   or die("Can't create \"$qfn\": $!\n");

for (1..1000) {
   print($fh "\0" x (1024*1024))
      or die("Error writing to \"$qfn\": $!\n");
}

close($fh)
   or die("Error writing to \"$qfn\": $!\n");

(Ok, so that's really equivalent to bs=1024k count=1KB, but the result is the same, and it's faster than bs=1KB count=1024k for both dd and for perl.)

ikegami
  • 367,544
  • 15
  • 269
  • 518