icon Top 9 categories map      RocketAware > Perl >

How do I randomly update a binary file?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.


Search Perl pages


By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Integer, Floating point, Matrix, Statistics, Boolean, ...

Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...


How do I randomly update a binary file?

If you're just trying to patch a binary, in many cases something as simple as this works:

    perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs

However, if you have fixed sized records, then you might do something more like this:

    $RECSIZE = 220; # size of record, in bytes
    $recno   = 37;  # which record to update
    open(FH, "+<somewhere") || die "can't update somewhere: $!";
    seek(FH, $recno * $RECSIZE, 0);
    read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!";
    # munge the record
    seek(FH, $recno * $RECSIZE, 0);
    print FH $record;
    close FH;

Locking and error checking are left as an exercise for the reader. Don't forget them, or you'll be quite sorry.

Don't forget to set binmode() under DOS-like platforms when operating on files that have anything other than straight text in them. See the docs on open() and on binmode() for more details.

Source: Perl FAQ: Files and Formats
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How do I get a file's timestamp in perl?

Previous: I still don't get locking. I just want to increment the number in the file. How can I do this?

(Corrections, notes, and links courtesy of RocketAware.com)

[Overview Topics]

Up to: Random Numbers

Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq5/How_do_I_randomly_update_a_binar.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments