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
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.
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.