读取没有最后 x 个字节的文件


Reading file without last x bytes

我想在 php 中读取没有最后 x 个字节的文件,就像这样:

$size = filesize($filename) - $x;
$handle = fopen($filename, "rb");
$contents = fread($handle, $size);
fclose($handle);

在我的应用程序中,我将大量使用此代码。

这有效,但是是否可以更简短,更灵活地执行此操作,而不是每次都使用(文件大小,fopen,fclose)?

file_get_contents()能帮忙吗?如果是这样,我该如何使用它?

例如

(非常简单的解决方案)

$contents = substr(file_get_contents($filename), 0, -$x);

只需删除最后的字节/字符。

它适用于file_get_contents()

$contents = file_get_contents($filename, false, null, 0, filesize($filename) - $x);