Using PHP rewind() Function to Reset the File Pointer
This article explains PHP's rewind() function, detailing its syntax, parameters, return values, and providing two practical code examples that demonstrate resetting a file pointer for both reading and writing operations within a.
PHP provides a rich set of functions for file manipulation, and one of them is rewind() . The rewind() function repositions the file pointer to the beginning of the file, allowing the file to be read again or other operations to be performed.
Usage:
rewind(resource $handle): boolParameter Description:
$handle : required. The file pointer resource.
Return Value:
Returns true on success, false on failure.
Example 1: Read file content and use rewind() to reset the pointer
$file = fopen("example.txt", "r");
// Read file content
while (!feof($file)) {
echo fgets($file) . "
";
}
// Reset pointer to the beginning
rewind($file);
// Read file content again
while (!feof($file)) {
echo fgets($file) . "
";
}
fclose($file);The code opens example.txt , reads and outputs its content, calls rewind() to move the pointer back to the start, and reads the content a second time.
Example 2: Use rewind() during file write operations
$file = fopen("example.txt", "w+");
// Write to the file
fwrite($file, "Hello, PHP!");
// Reset pointer to the beginning
rewind($file);
// Read the written content
echo fgets($file);
fclose($file);This example creates a new file with mode w+ , writes a string, rewinds the pointer, and then reads back the written content.
Summary:
By using the rewind() function, developers can easily reposition the file pointer to the start of a file, enabling repeated reads or further processing after writing. Ensure the file is opened before calling rewind() , and combine it with other file‑handling functions as needed.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.