Open In App

PHP | rewind( ) Function

Last Updated : 22 May, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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, 'geeksforgeeks');
        rewind($myfile);
        fwrite($myfile, 'portal');
        rewind($myfile);
        echo fread($myfile, filesize("gfg.txt"));
        fclose($myfile);

Output : portalforgeeks
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, 'geeksforgeeks a computer science portal');
  
// Setting the file pointer to 0th
// position using rewind() function
rewind($myfile);
  
// writing to file on 0th position
fwrite($myfile, 'geeksportal');
rewind($myfile);
  
// displaying the contents of the file
echo fread($myfile, filesize("gfg.txt"));
  
fclose($myfile);
  
?>


Output:

geeksportalks a computer science portal

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads