6.16 Changing a Specific Record


You need to read a particular record from a binary file containing fixed-length records, change the value of the record, and then write the record back.

Technique

Read the old record, pack the updated values, seek to the previous address, and then write the updated record back to the file:

 <?php $address = $record_number * $record_size; fseek ($fp, $address); $f_contents = fread ($fp, $record_size); $fields = array_values (unpack ($format_specifier, $f_contents)); // ... update the fields here $f_contents = pack ($format_specifier, implode ("", $fields)); fseek ($fp, -$record_size); fwrite ($fp, $f_contents); @fclose ($fp); ?> 

Comments

This recipe is pretty much what it appears to be. On the first line, we find the address where the record starts. On the second line, we seek to that address, and then read the contents into $f_contents (notice the binary-safe fread() ). Then we unpack the values of the record; array_values() makes it a regular, not associative, array. Finally, we pack the record back into its original format. (Note that we implode the array around " " instead of "\0" because \0 is a binary end of line.) Then we write the record back to the file (again notice that fwrite() is binary-safe) and close the file.

This will work only for fixed-length records ”any other type would cause the file to lose its integrity.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net