Using PHP fseek() to Position File Pointers
This article explains PHP's fseek() function, detailing its syntax, parameters such as offset and whence, and demonstrates practical usage with example code to move file pointers, read, write, and manage file contents efficiently.
In PHP file operations, it is often necessary to position the file pointer at a specific location; the built‑in fseek() function provides this capability.
The fseek() function moves the file pointer within an opened file, allowing subsequent read, write, or append actions.
Its syntax is: fseek(file, offset, whence) file (required): the file resource, typically obtained via fopen() .
offset (required): the number of bytes to move; positive moves forward, negative moves backward, zero leaves the pointer unchanged.
whence (optional): determines how the offset is applied; possible values are SEEK_SET (beginning of file, default), SEEK_CUR (current position), and SEEK_END (end of file).
Example usage:
<?php
$file = fopen("example.txt", "r+");
if ($file) {
// Move pointer to start of file
fseek($file, 0, SEEK_SET);
// Read first 10 bytes
echo fread($file, 10);
// Move pointer to end of file
fseek($file, 0, SEEK_END);
// Write new line
fwrite($file, "This is a new line.");
// Move pointer back to start
fseek($file, 0, SEEK_SET);
// Read entire file
echo fread($file, filesize("example.txt"));
// Close file
fclose($file);
}
?>The script opens a file with fopen(), uses fseek() to reposition the pointer, reads and writes data with fread() and fwrite(), and finally closes the file.
Overall, fseek() is a flexible and essential function for precise file manipulation in PHP.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
