簡易まとめ
使用した関数
sample
//$file_pathにあるファイルを開く
$open_file = fopen($file_path, 'r');
//ポインターの場所を取得
ftell($open_file)
//ポインターある位置の文字を取得する
fgetc($open_file)
//ポインターがある位置からその行の最後までを取得する。また、ポインターが取得したバイト数分移動する
fgets($open_file)
//ポインターの場所をファイルの先頭から指定したバイト数分移動した位置に変更する
fseek($open_file, bytes)
例
example.txt
1line
2line
3line
4line
5line
example.php
<?php
$file_path = "./example.txt"; //pathは自分の環境似合わせてね!
$open_file = fopen($file_path, 'r');
echo("何もしていない時のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file));
echo("fgets()を一回実行した後のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file));
fseek($open_file, 6);
echo("fseek($open_file, 6)を実行した後のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file)."\n");
//おまけ
fseek($open_file, 1);
echo(fgetc($open_file)."\n");
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
?>
terminalでphp ./example.php
を実行する
結果
何もしていない時のポインター位置: 0
1line
fgets()を一回実行した後のポインター位置: 6
2line
fseek(Resource id #5, 6)を実行した後のポインター位置: 6
2line
l
ine
2line
3line
4line
5line