A companion script to the one in Finding differences in binary files, written for testing purposes and posted here for the same reasons.

Alterates randomly a number (currently hardcoded, it's the value of $LEN) of consecutive bytes in a binary file:

#!/usr/bin/perl use strict; use warnings; die "Usage: $0 file\n" unless @ARGV == 1; my $fn=shift; my $LEN=3; my $cont = do { open my $fh, '<:raw', $fn or die "$fn: D'Oh! $!\n"; local $/; <$fh>; }; open my $fh, '>:raw', $fn or die "$fn: D'Oh! $!\n"; print $fh $cont ^ do { "\0" x rand(-$LEN + length $cont) . join '', map { chr rand 0x100 } 1 .. $LEN; }; __END__
--
If you can't understand the incipit, then please check the IPB Campaign.

Replies are listed 'Best First'.
Re: Randomly mangle a binary file
by jwkrahn (Abbot) on Sep 01, 2008 at 12:33 UTC

    You don't have to read the whole file just to modify three bytes:

    #!/usr/bin/perl use strict; use warnings; use Fcntl ':seek'; die "Usage: $0 file\n" unless @ARGV == 1; my $fn = shift; my $LEN = 3; open my $fh, '+<:raw', $fn or die "$fn: D'Oh! $!\n"; my $offset = rand( -$LEN + -s $fh ); seek $fh, $offset, SEEK_SET or die "$fn: D'Oh! $!\n"; read $fh, my $cont, $LEN; seek $fh, $offset, SEEK_SET or die "$fn: D'Oh! $!\n"; print $fh $cont ^ join '', map chr( rand 0x100 ), 1 .. $LEN; __END__
      You don't have to read the whole file just to modify three bytes:

      Actually, I knew: I didn't use "your" technique, because I'm less familiar with it and the whole point of the program was to create a test case that were "small enough." (I just wanted to... get it done, if you know what I mean!) Indeed, not only is your approach more efficient, but it is even simpler as a whole: well done mentioning it!

      seek $fh, $offset, SEEK_SET or die "$fn: D'Oh! $!\n"; read $fh, my $cont, $LEN; seek $fh, $offset, SEEK_SET or die "$fn: D'Oh! $!\n"; print $fh $cont ^ join '', map chr( rand 0x100 ), 1 .. $LEN;

      (Incidentally, there's a typo that makes for a syntax error: missing parens around my $cont.)

      It can be even easier than that: given that we're xoring with completely random bytes (as opposed, say, to bytes with a prescribed number of bits on) we may avoid doing so altogether and just print them, thus:

      #!/usr/bin/perl use strict; use warnings; use Fcntl ':seek'; die "Usage: $0 file\n" unless @ARGV == 1; my $fn = shift; my $LEN = 3; open my $fh, '+<:raw', $fn or die "$fn: D'Oh! $!\n"; seek $fh, rand(-$LEN + -s $fh), SEEK_SET or die "$fn: D'Oh! $!\n"; print $fh map chr rand 0x100, 1 .. $LEN; __END__

      Oh my!

      --
      If you can't understand the incipit, then please check the IPB Campaign.