Understanding and Using the PHP fseek() Function
The article explains the purpose and syntax of PHP's fseek() function, details its parameters—including file, offset, and whence options such as SEEK_SET, SEEK_CUR, and SEEK_END—provides a complete example demonstrating file opening, pointer positioning, reading, writing, and closing operations.
The fseek() function moves the file pointer to a specified location, enabling various file operations such as reading, writing, or appending data.
Syntax of fseek()
<code>fseek(file, offset, whence)</code>file : required; the file resource opened by fopen() .
offset : required; the number of bytes to move the pointer (positive, negative, or zero).
whence : optional; determines how the offset is interpreted. Possible values 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 of fseek()
<code><?php
$file = fopen("example.txt", "r+");
if ($file) {
// Move pointer to the beginning
fseek($file, 0, SEEK_SET);
// Read first 10 bytes
echo fread($file, 10);
// Move pointer to the end
fseek($file, 0, SEEK_END);
// Write new line
fwrite($file, "This is a new line.");
// Move pointer back to the beginning
fseek($file, 0, SEEK_SET);
// Read entire file
echo fread($file, filesize("example.txt"));
// Close file
fclose($file);
}
?>
</code>The example opens a file in read‑write mode, uses fseek() to position the pointer at the start, reads bytes, moves to the end, writes new data, returns to the start, reads the whole file, and finally closes it.
Overall, fseek() is a flexible and essential PHP function for precise file positioning, allowing developers to add, delete, or modify data efficiently.
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.