3

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

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

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

这可行,但是是否可以更简单、更灵活地执行此操作,而不是每次都使用 (filesize, fopen, fclose)?

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

4

2 回答 2

6

例如(非常简单的解决方案)

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

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

于 2012-08-11T23:29:57.233 回答
2

它适用于file_get_contents()

$contents = file_get_contents($filename, false, null, 0, filesize($filename) - $x);
于 2012-08-11T23:31:09.673 回答