PHP » I/O » fseek()

int fseek(int file, int offset [, int whence])
File handle of the file.
Number of bytes to move the pointer.
Where the offset is counted from.

Moves the file pointer.

Files have an internal pointer keeping track of the current position for reading and writing. This pointer can be moved to an arbitrary position with the fseek() function. There are three different possible values for whence that affect how the offset is used. The default value for the parameter whence is SEEK_SET, which means that it is an offset from the beginning of the file. whence can also be SEEK_CUR, which gives an offset relative to the current position, and SEEK_END, meaning an offset from the end of the file. On success 0 is returned, otherwise -1 is returned.



$filename = "log.txt";

$logfile = fopen($filename, "r");

// find the length of an entry
$line = fgets($logfile);
$entry_length = strlen($line);

// read the 4th entry
fseek($logfile, $entry_length * 3);
$line = fread($logfile, $entry_length);

print "The 4th entry is: $line";

The 4th entry is: Sample code running

With fseek(), there is no need to read all the way from the beginning of a file to read a portion in the middle of the file. One situation where this is useful is when there are entries of a fixed length in a file. This is demonstrated with this code and our logfile that only has lines of the same length.

See Also: