関数 fseek

関数 fseek は、ファイル内の位置ポインタを移動させることができます。第一引数にはファイルポインタを、第二引数にはバイト単位のオフセットを、第三引数(オプション)には基準点を取ります。関数は成功時に0を、エラー時に-1を返します。

構文

phpfseek(resource $handle, int $offset, int $whence = SEEK_SET): int

例

ファイルの先頭から10バイト目にポインタを移動します:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, 10);
  echo fgets($file);
  fclose($file);
?>

例

現在の位置から5バイト先にポインタを移動します:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, 5, SEEK_CUR);
  echo fgets($file);
  fclose($file);
?>

例

ファイルの末尾から5バイト手前にポインタを移動します:

php<?php
  $file = fopen('test.txt', 'r');
  fseek($file, -5, SEEK_END);
  echo fgets($file);
  fclose($file);
?>

例

fseekの実行結果を確認します:

php<?php
  $file = fopen('test.txt', 'r');
  $res = fseek($file, 10);
  echo $res; // 成功時は0、エラー時は-1
  fclose($file);
?>

コードの実行結果:

php0

関連項目

  • ファイルポインタを先頭に巻き戻す関数 rewind
  • 現在の位置を返す関数 ftell
  • ファイルから読み込む関数 fread