user5861285
user5861285

Reputation:

How to get the last 16 bytes from binary file with Perl?

I read an image with Perl read:

open (FILE,"<$filename") or die $!;
            binmode FILE;
            while (($n = read FILE, $data, 4) != 0) {
                $buf .= $data;
            }
close (FILE);

How can i get only the last 16 bytes from this file? Backgound is, that i want to compare the last 16 bytes from an image with the last 16 bytes from another image.

Upvotes: 2

Views: 652

Answers (1)

Markus Laire
Markus Laire

Reputation: 2947

Use seek to move to position 16 bytes before file end, and then read the 16 bytes:

open (FILE, "<$filename") or die $!;
binmode FILE;
seek FILE, -16, 2;
read FILE, $data, 16;
close (FILE);

You can also use constant instead of 2:

use Fcntl qw(SEEK_END);

open (FILE, "<$filename") or die $!;
binmode FILE;
seek FILE, -16, SEEK_END;
read FILE, $data, 16;
close (FILE);

Upvotes: 5

Related Questions