溫馨提示×

fseek php 如何實現(xiàn)文件定位

PHP
小樊
81
2024-09-24 00:07:50
欄目: 編程語言

在 PHP 中,可以使用 fseek() 函數(shù)來實現(xiàn)文件的定位

<?php
$file = fopen('example.txt', 'r');

// 將文件指針移動到第 10 個字節(jié)的位置
fseek($file, 10);

// 讀取從當前文件指針位置開始的一段內(nèi)容
$content = fread($file, 5);
echo "Read content: " . $content; // 輸出:Read content: el

// 將文件指針移回文件開頭
fseek($file, 0);

// 讀取整個文件內(nèi)容
$content = fread($file, filesize('example.txt'));
echo "Read content: " . $content; // 輸出:Read content: example content

// 關閉文件
fclose($file);
?>

在這個示例中,我們首先打開一個名為 example.txt 的文件,并將其內(nèi)容讀取到 $content 變量中。然后,我們使用 fseek() 函數(shù)將文件指針移動到第 10 個字節(jié)的位置,并讀取從當前文件指針位置開始的一段內(nèi)容。接下來,我們將文件指針移回文件開頭,并讀取整個文件內(nèi)容。最后,我們關閉文件。

0