PHP Velho Oeste 2024

SplFileObject::fseek

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fseekファイルポインタを移動させる

説明

public SplFileObject::fseek(int $offset, int $whence = SEEK_SET): int

offsetwhence で指定される位置に追加することで、ファイルの始めからバイト単位でファイルポイントを移動させます。

パラメータ

offset

オフセットです。負の値はポインタを戻すために使うことができます。これは SEEK_END が whence の値として使われるときに便利です。

whence

whence の値は次のようなものになります:

  • SEEK_SET - offset バイトに等しい位置にセットします。
  • SEEK_CUR - 現在の位置に offset を加えた位置にセットします。
  • SEEK_END - 終端に offset を加えた位置にセットします。

whence が指定されない場合、SEEK_SET が前提になります。

戻り値

探索が成功した場合は 0、そうでなければ -1 が返されます。終端より先の位置を探索してもエラーにならないことにご注意してください。

例1 SplFileObject::fseek() の例

<?php
$file
= new SplFileObject("somefile.txt");

// 最初の行を読み込む
$data = $file->fgets();

// ファイルの最初に戻る
// $file->rewind(); と同じ
$file->fseek(0);
?>

参考

  • fseek() - ファイルポインタを移動する

add a note add a note

User Contributed Notes 1 note

up
-7
wangbuying at gmail dot com
10 years ago
make sure you know this fseek in SplFileObject is different from \fseek.
Argument for fseek in SplFileObject is the line number, not the bytes.
Example:
<?php
$fp
= new SplFileObject('./fseek.txt', 'rb');
$fp->fseek(70); // now go to line 70, not byte 70
echo $fp->fgets();
?>
To Top