fseek()
is a built-in function in PHP.
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 following is the function prototype:
fseek(file, offset, whence)
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.
<?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 pointerfclose($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