Specifications
Navigating Inside a File: rewind(), fseek(), and ftell()
You can manipulate and discover the position of the file pointer inside a file using rewind(),
fseek(), and ftell().
The rewind() function resets the file pointer to the beginning of the file. The ftell() function
reports how far into the file the pointer is in bytes. For example, we can add the following lines
to the bottom of our original script (before the fclose() command):
echo “Final position of the file pointer is “.(ftell($fp));
echo “<br>”;
rewind($fp);
echo “After rewind, the position is “.(ftell($fp));
echo “<br>”;
The output in the browser will be similar to that shown in Figure 2.5.
Using PHP
P
ART I
64
FIGURE 2.5
After reading the orders, the file pointer points to the end of the file, an offset of 234 bytes. The call to rewind sets it
back to position 0, the start of the file.
The function fseek() can be used to set the file pointer to some point within the file. Its proto-
type is
int fseek(int fp, int offset);
A call to fseek() sets the file pointer fp at a point offset bytes into the file. The rewind()
function is equivalent to calling the fseek() function with an offset of zero. For example, you
can use
fseek() to find the middle record in a file or to perform a binary search. Often if you
reach the level of complexity in a data file where you need to do these kinds of things, your
life will be much easier if you used a database.
04 7842 CH02 3/6/01 3:37 PM Page 64