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

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.

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)

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.

See Also

Documentation on ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.