Backend Development 5 min read

Using PHP fseek() to Move File Pointers: Definition, Parameters, Return Values, and Practical Examples

This article explains the PHP fseek() function, detailing its signature, parameters, return values, and demonstrates how to move a file pointer, read specific portions, and write data at a given offset with clear code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fseek() to Move File Pointers: Definition, Parameters, Return Values, and Practical Examples

In PHP, the fseek() function moves the file pointer to a specified position, allowing reading or writing at different parts of a file.

Function Definition

Signature

<code>int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )</code>

Parameters

handle : the file pointer resource (required).

offset : number of bytes to move; negative values move toward the file start (required).

whence : optional; determines the reference point and can be SEEK_SET (default, from start), SEEK_CUR (from current position), or SEEK_END (from end).

Return Value

Returns 0 on success, -1 on failure.

Function Usage

The fseek() function is used to reposition the file pointer for subsequent read or write operations.

Moving the File Pointer

Example of moving the pointer to the 10th byte of a file:

<code>$file_handle = fopen("file.txt", "r");
fseek($file_handle, 10);</code>

This code opens file.txt with fopen() , stores the handle in $file_handle , and moves the pointer to byte 10 using fseek() .

Reading File Content

To read 20 bytes starting from the 10th byte:

<code>$file_handle = fopen("file.txt", "r");
fseek($file_handle, 10);
$content = fread($file_handle, 20);</code>

The pointer is positioned with fseek() , then fread() reads the next 20 bytes.

Writing File Content

To write "Hello World" at the 10th byte:

<code>$file_handle = fopen("file.txt", "w");
fseek($file_handle, 10);
fwrite($file_handle, "Hello World");</code>

After opening the file with fopen() and moving the pointer, fwrite() writes the string at the specified offset.

Summary

The fseek() function is essential for moving the file pointer within a file, enabling precise reading and writing operations; this article covered its definition, parameters, return values, and provided practical examples for moving, reading, and writing file data.

Backendfile-iofseekfile-pointer
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.