Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the fseek() function in PHP?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring