What is the fseek() function in PHP?

fseek() is a built-in function in PHP.

Functionality

The fseek() function seeks a specified file. It moves the file pointer from its current position to a new position.

The new position is specified by the number of bytes and may be forward or backward, relative to the current position of the file pointer.

For example, an offset (or byte number) of 0 moves the pointer to the start of the file.

The fseek() function

Syntax

The following is the function prototype:

fseek(file, offset, whence) 

Parameters and return value

The fseek() function takes the following input parameters:

  • file: The name of the file.
  • offset: The new position, in bytes, of the file pointer.
  • whence: An optional parameter that can have the values in the table below:

Value

Description

SEEK_SET

Sets the file pointer to the offset. Default functionality.

SEEK_CUR

Sets the file pointer to the current position plus offset.

SEEK_END

Sets the file pointer to EOF plus offset. To move to a position before EOF, offset must be negative.

The function returns 0 on success. Otherwise, it returns -1.

Code

main.php
Edpresso.txt
<?php
$fp = fopen("Edpresso.txt", "r");
fgets($fp);
// Move to byte number 2 (p)
echo "Output: ", fseek($fp, 2);
echo "\n";
echo fgetc($fp); # Read data pointed by file pointer
fclose($fp);
?>

In the example above, we open the file Edpresso.txt. Next, we use fseek() to move to the second byte of the file.

The fgetc() function reads the character pointed to by the file pointer.

Finally, the character is displayed on the screen. The output for fseek() is 0, demonstrating successful execution.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved