PHP SplFileObject fseek() Function
Last Updated :
18 Sep, 2023
The SplFileObject::fseek() function is an inbuilt function of Standard PHP Library (SPL) in PHP that allows you to move the file pointer to a specified position within a file opened using SplFileObject
. The file pointer is the position where the next read or write operation will occur. This function is used to navigate within a file and read or write data from a specific location.
Syntax:
public SplFileObject::fseek(int $offset, int $whence = SEEK_SET): int
Parameters: This function accepts two parameters that are described below.
- $offset: The offset value represents the number of bytes to move the file pointer. It can be positive or negative, depending on the direction you want to move the pointer.
- $whence: This is an optional parameter that specifies the starting point for the offset calculation. It can take one of the following values:
SEEK_SET
– Set position equal to offset
bytes, SEEK_CUR
– Set position to current location plus offset
, SEEK_END
– Set position to end-of-file plus offset
.
Program 1: The following program demonstrates the SplFileObject::fseek() function. Save this file name as “output.txt” before running this program.
Line 1: This is the first line of data.
Line 2: This is the second line of data.
Line 3: This is the third line of data.
PHP
<?php
$file = new SplFileObject( './output.txt' , 'r' );
$file -> fseek (10, SEEK_SET);
$content = $file -> fread ( $file ->getSize() - $file -> ftell ());
echo $content ;
?>
|
Output:
is is the first line of data.
Line 2: This is the second line of data.
Line 3: This is the third line of data.
Program 2: The following program demonstrates the SplFileObject::fseek() function. Save this file name as “output.txt” before running this program.
Ram
Seeta
Michael Johnson
Emily Brown
William Davis
PHP
<?php
$file = new SplFileObject( 'output.txt' , 'r' );
$file -> fseek ( strlen ( "Michael \n" ) * 2, SEEK_SET);
$thirdName = trim( $file -> fgets ());
echo "The third name in the file is: " . $thirdName ;
?>
|
Output:
The third name in the file is: Johnson
Reference: https://www.php.net/manual/en/splfileobject.fseek.php
Share your thoughts in the comments
Please Login to comment...