Wednesday, November 20, 2024
Google search engine
HomeLanguagesPHP | rewind( ) Function

PHP | rewind( ) Function

The rewind() function in PHP is an inbuilt function which is used to set the position of the file pointer to the beginning of the file.
Any data written to a file will always be appended if the file is opened in append (“a” or “a+”) mode regardless of the file pointer position.
The file on which the pointer has to be edited is sent as a parameter to the rewind() function and it returns True on success or False on failure.

Syntax:

rewind(file)

Parameters Used:
The rewind() function in PHP accepts one parameter.

  • file : It is a mandatory parameter which specifies the file to be edited.

Return Value:
It returns True on success or False on failure.

Errors And Exception:

  1. The rewind() function generates an E_WARNING level error on failure.
  2. The stream must be “seekable” for using the rewind() function.
  3. If the file is opened in append mode, the data written will be appended regardless of the position of the pointer.

Examples:

Input: $myfile = fopen("gfg.txt", "r");
        fseek($myfile, "10");
        rewind($myfile);
        fclose($file);

Output: 1

Input : $myfile = fopen("gfg.txt", "r+");
        fwrite($myfile, 'neveropen');
        rewind($myfile);
        fwrite($myfile, 'portal');
        rewind($myfile);
        echo fread($myfile, filesize("gfg.txt"));
        fclose($myfile);

Output : portalforneveropen
Here all characters of the file as it is after rewind "portal"

Below are the programs to illustrate the rewind() function.

Program 1




<?php
  
$myfile = fopen("gfg.txt", "r");
  
// Changing the position of the file pointer
fseek($myfile, "10");
  
// Setting the file pointer to 0th 
// position using rewind() function
rewind($myfile);
  
// closing the file
fclose($file);
  
?>


Output:

1

Program 2




<?php
  
$myfile = fopen("gfg.txt", "r+");
  
// writing to file
fwrite($myfile, 'neveropen a computer science portal');
  
// Setting the file pointer to 0th
// position using rewind() function
rewind($myfile);
  
// writing to file on 0th position
fwrite($myfile, 'neveropenportal');
rewind($myfile);
  
// displaying the contents of the file
echo fread($myfile, filesize("gfg.txt"));
  
fclose($myfile);
  
?>


Output:

neveropenportalks a computer science portal

Reference:
http://php.net/manual/en/function.rewind.php

RELATED ARTICLES

Most Popular

Recent Comments