【发布时间】:2025-12-02 23:25:01
【问题描述】:
读取.txt文件,得到文本文件的最后一行,我使用的函数在下面注释
function read_last_line (){
$line = '';
$f = fopen('localpath\data.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
/**
* Trim trailing newline chars of the file
*/
while ($char === "\n" || $char === "\r") {
fseek($f, $cursor--, SEEK_END);
$char = fgetc($f);
}
/**
* Read until the start of the file or first newline char
*/
while ($char !== false && $char !== "\n" && $char !== "\r") {
/**
* Prepend the new char
*/
$line = $char . $line;
fseek($f, $cursor--, SEEK_END);
$char = fgetc($f);
}
echo $line;
}
在执行上面的代码时,我得到了fseek(): stream does not support seeking,需要一个解决方案来解决这个问题。
【问题讨论】:
-
来自documentation 它指出并非所有流都是可搜索的,您应该在代码中处理这个问题。您可以尝试使用 SplFileObject (*.com/questions/9763822/…)
-
不适合处理大文件,但比您尝试做的要简单:
$lastLine = end($lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));