Hàm fseek
Hàm fseek cho phép di chuyển con trỏ vị trí trong file. Tham số đầu tiên nó nhận một con trỏ tới file, tham số thứ hai - offset tính bằng byte, và tham số thứ ba (tùy chọn) - điểm tham chiếu. Hàm trả về 0 nếu thực hiện thành công và -1 nếu có lỗi.
Cú pháp
fseek(resource $handle, int $offset, int $whence = SEEK_SET): int
Ví dụ
Di chuyển con trỏ tới byte thứ 10 tính từ đầu file:
<?php
$file = fopen('test.txt', 'r');
fseek($file, 10);
echo fgets($file);
fclose($file);
?>
Ví dụ
Di chuyển con trỏ 5 byte từ vị trí hiện tại:
<?php
$file = fopen('test.txt', 'r');
fseek($file, 5, SEEK_CUR);
echo fgets($file);
fclose($file);
?>
Ví dụ
Di chuyển con trỏ 5 byte từ cuối file:
<?php
$file = fopen('test.txt', 'r');
fseek($file, -5, SEEK_END);
echo fgets($file);
fclose($file);
?>
Ví dụ
Kiểm tra kết quả thực thi của fseek:
<?php
$file = fopen('test.txt', 'r');
$res = fseek($file, 10);
echo $res; // 0 nếu thành công, -1 nếu có lỗi
fclose($file);
?>
Kết quả thực thi mã:
0