Mastering PHP’s fseek(): Precise File Pointer Control
This article explains how PHP’s fseek() function moves the file pointer to any position, details its syntax and parameters, and provides a complete example demonstrating reading, writing, and seeking within a file for flexible file manipulation.
In PHP file operations, you often need to position the file pointer at a specific location; the built-in fseek() function serves this purpose.
The fseek() function moves the file pointer to a given offset, enabling reading, writing, or appending data at arbitrary positions.
Syntax: fseek(file, offset, whence) file (required): the file resource opened with fopen().
offset (required): the number of bytes to move; positive moves forward, negative moves backward, zero stays.
whence (optional): determines how the offset is applied. Options are:
SEEK_SET (default): set pointer to the beginning of the file.
SEEK_CUR: set pointer relative to the current position.
SEEK_END: set pointer relative to the end of the file.
Example usage:
<?php
$file = fopen("example.txt", "r+");
if ($file) {
// Move pointer to the start
fseek($file, 0, SEEK_SET);
// Read first 10 bytes
echo fread($file, 10);
// Move pointer to the end
fseek($file, 0, SEEK_END);
// Write a new line
fwrite($file, "This is a new line.");
// Return to the start
fseek($file, 0, SEEK_SET);
// Output the whole file
echo fread($file, filesize("example.txt"));
fclose($file);
}
?>The script opens a file in read‑write mode, uses fseek() to jump to the start, reads the first 10 bytes, moves to the end to append a line, then returns to the beginning to read and display the entire file before closing it.
Overall, fseek() is a flexible and essential function for precise file positioning, enabling efficient addition, deletion, and modification of data within files.
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.
