Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

File reading with sysseek and sysread

by PhilHibbs (Hermit)
on Dec 02, 2005 at 10:59 UTC ( #513557=perlquestion: print w/ replies, xml ) Need Help??
PhilHibbs has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to open files, seek to particular offsets, and read the byte value at that offset. My input file is the output of a number of executions of the Windows command FC /B which does a binary comparison of two files. I want to pick up the second filename (this works), seek to the offset mentioned in the driver file, read the byte at that position, and print out the hex value. Here's my code, and an example input file:
my $buf = ' '; while (<>) { if (/Comparing files (.+) and (.+)/) { open FH,">>$2" or die "Can't open $2\n"; binmode FH; print "Opening $2\n"; } if (/([0-9A-F]{8}): ([0-9A-F]{2}) ([0-9A-F]{2})$/ and $3 gt $2) { sysseek FH,hex($1),0; print "Seek $1 (".hex($1).")\n"; sysread FH,$buf,1; print "Read ".sprintf("%2.2x",ord($buf))."\n"; } } __END__ Comparing files C:\PROGRAM FILES\PROJECT ENTROPIA\DATA\MODELS\Models.b +nt and C:\DATA\MODELS\MODELS.BNT 05063755: 03 43 0875CF55: BF FF 09DC0155: 00 40 0B209955: 40 00 0DE8AD55: 0A 4A 0DF4ED55: 7F 3F Comparing files C:\PROGRAM FILES\PROJECT ENTROPIA\DATA\TERRAIN\50.bnt +and C:\DATA\TERRAIN\50.BNT 03040155: 15 55 Comparing files C:\PROGRAM FILES\PROJECT ENTROPIA\DATA\TEXTURES\Textur +es.bnt and C:\DATA\TEXTURES\TEXTURES.BNT 088C1355: 4C 0C 10F45955: 40 00 1155A355: 1E 5E 181FDB55: A6 E6
It always prints out 20, which is the space that I am initializing $buf with. What am I doing wrong?

Replies are listed 'Best First'.
Re: File reading with sysseek and sysread
by ysth (Canon) on Dec 02, 2005 at 11:04 UTC
    Check for error returns from sysseek and sysread and show $! if they do give errors.

    Gah. Consider opening FH for read access, not append.

      Surely append access also grants read access. I've changed it to "+<$2" and it works now! Thanks!
        Surely append access also grants read access.
        No, it doesn't :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://513557]
Approved by ysth
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2016-06-25 22:34 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (327 votes). Check out past polls.