8.14. Reading a String from a Binary File8.14.1. ProblemYou want to read a NUL-terminated string from a file, starting at a particular address. 8.14.2. SolutionEnsure you're working with a binary file, set $/ to an ASCII NUL, and read the string with <>: binmode(FH); # binary mode $old_rs = $/; # save old $/ $/ = "\0"; # ASCII 0: NUL seek(FH, $addr, SEEK_SET) or die "Seek error: $!\n"; $string = <FH>; # read string chomp $string; # remove NUL $/ = $old_rs; # restore old $/ You can use local to save and restore $/:
8.14.3. DiscussionThe example program shown in Example 8-5, bgets, accepts a filename and one or more byte addresses as arguments. Decimal, octal, or hexadecimal addresses may be specified. For each address, the program reads and prints the null- or EOF-terminated string at that position. Example 8-5. bgets
Example 8-6 is a simple implementation of the Unix strings program. Example 8-6. strings
8.14.4. See AlsoThe PerlIO(3) manpage; the seek, getc, and ord functions in perlfunc(1) and in Chapter 29 of Programming Perl; the discussion of qq// in the "Quote and Quote-Like Operators" section of the perlop(1) manpage, and in the "Pick Your Own Quotes" section of Chapter 2 of Programming Perl
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|