Master PHP’s ftell(): How to Get File Pointer Position with Code Examples
This article explains how to use PHP's ftell() function to retrieve the current file pointer position, covering its signature, parameters, return values, and providing a practical code example that reads the first ten bytes of a file and displays the pointer offset.
In PHP programming, reading and writing files often requires knowing the current file pointer position; the
ftell()function provides this capability.
This article introduces the usage of
ftell()with code examples.
Function Overview:
<code>ftell(resource $handle): int</code>The function returns the current position of the file pointer in the byte stream for the handle provided, or false on error.
Parameter Description:
$handle: file resource handle obtained via
fopen()or similar functions.
Return Value:
Returns the byte offset of the current file pointer, or false on failure.
Code Example:
The following example reads the first 10 bytes of a file and obtains the pointer position using
ftell():
<code><?php
$filename = "example.txt";
$handle = fopen($filename, "r");
if ($handle) {
$content = fread($handle, 10);
echo "File content: " . $content . "<br/>";
$position = ftell($handle);
echo "File pointer position: " . $position;
fclose($handle);
} else {
echo "Unable to open file!";
}
?></code>Assuming
example.txtcontains "Hello, World!", the output is:
<code>File content: Hello, Wor
File pointer position: 10</code>The script opens the file with
fopen(), reads 10 bytes with
fread(), prints the content, then uses
ftell()to retrieve and display the pointer position, and finally closes the file with
fclose().
Note that
ftell()returns the byte offset; when a file is opened in text mode, characters such as Chinese characters may occupy multiple bytes, so the offset is calculated in bytes.
Conclusion:
The
ftell()function is a useful tool in PHP file operations, allowing developers to obtain the current file pointer position and combine it with other file functions to enhance code efficiency.
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.