start page | rating of books | rating of authors | reviews | copyrights

Perl Cookbook

Perl CookbookSearch this book
Previous: 8.11. Processing Binary Files Chapter 8
File Contents
Next: 8.13. Updating a Random-Access File
 

8.12. Using Random-Access I/O

Problem

You have to read a binary record from the middle of a large file but don't want to read a record at a time to get there.

Solution

Once you know the record's size, multiply it by the record number to get the byte address, and then seek to that byte address and read the record:

$ADDRESS = $RECSIZE * $RECNO; seek(FH, $ADDRESS, 0) or die "seek:$!"; read(FH, $BUFFER, $RECSIZE);

Discussion

The Solution assumes the first record has a RECNO of 0. If you're counting from one, use:

$ADDRESS = $RECSIZE * ($RECNO-1);

This won't work on a text file unless all lines are the same length. This is rarely the case.

See Also

The seek function in perlfunc (1) and in Chapter 3 of Programming Perl ; Recipe 8.13


Previous: 8.11. Processing Binary Files Perl Cookbook Next: 8.13. Updating a Random-Access File
8.11. Processing Binary Files Book Index 8.13. Updating a Random-Access File

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.