PHP fseek() Function

Definition

The fseek() function seeks in an open file, by moving the file pointer from its current position to a new position, forward or backward, specified by the number of bytes.

Syntax

PHP fseek() Function has the following syntax.

fseek(file,offset,whence)

Parameter

ParameterIs RequiredDescription
fileRequired.Open file to seek in
offsetRequired.New position (measured in bytes from the beginning of the file)
whenceOptional.Option

Possible values for whence:

  • SEEK_SET - Set position equal to offset. Default
  • SEEK_CUR - Set position to current location plus offset
  • SEEK_END - Set position to EOF plus offset to move to a position before EOF, the offset must be a negative value

Return

This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error.

Example

fseek() moves a file handle pointer to an arbitrary position.


<?PHP/* www. ja  v a2  s .  co  m*/
      $filename = "c:/abc/test.txt";
      $handle = fopen($filename, "w+");
      fwrite($handle, "java2s.com\n");
      rewind($handle);
      fseek($handle, 1);
      fwrite($handle, "o");
      fseek($handle, 2, SEEK_CUR);
      fwrite($handle, "e");
      fclose($handle);
?>

The first byte of a file is byte 0, and you count upward from there. The second byte is at index 1, the third at index 2, etc.

Find the current position by using ftell().





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions