Book HomePHP CookbookSearch this book

18.15. Reading from or Writing to a Specific Location in a File

18.15.1. Problem

You want to read from (or write to) a specific place in a file. For example, you want to replace the third record in a file of 80-byte records, so you have to write starting at the 161st byte.

18.15.2. Solution

Use fseek( ) to move to a specific number of bytes after the beginning of the file, before the end of the file, or from the current position in the file:

fseek($fh,26);           // 26 bytes after the beginning of the file
fseek($fh,26,SEEK_SET);  // 26 bytes after the beginning of the file
fseek($fh,-39,SEEK_END); // 39 bytes before the end of the file
fseek($fh,10,SEEK_CUR);  // 10 bytes ahead of the current position
fseek($fh,0);            // beginning of the file

The rewind( ) function moves to the beginning of a file:

rewind($fh);             // the same as fseek($fh,0)

18.15.3. Discussion

The function fseek( ) returns 0 if it can move to the specified position, otherwise it returns -1. Seeking beyond the end of the file isn't an error for fseek( ). Contrastingly, rewind( ) returns 0 if it encounters an error.

You can use fseek( ) only with local files, not HTTP or FTP files opened with fopen( ). If you pass a file handle of a remote file to fseek( ), it throws an E_NOTICE error.

To get the current file position, use ftell( ) :

if (0 === ftell($fh)) {
  print "At the beginning of the file.";
}

Because ftell( ) returns false on error, you need to use the === operator to make sure that its return value is really the integer 0.

18.15.4. See Also

Documentation on fseek( ) at http://www.php.net/fseek, ftell( ) at http://www.php.net/ftell, and rewind( ) at http://www.php.net/rewind.



Library Navigation Links

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