gpt4 book ai didi

php - 使用 PHP 在末尾截断文件

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:02 25 4
gpt4 key购买 nike

我有一个日志文件,我想在它被 PHP 读取后截断。我的代码目前看起来像这样:

$fp = fopen($file, "r+");
ftruncate($fp, 125000);
fclose($fp);

但是,这会通过保留第一个 1Mb 来截断文件。但是,我想保留文件的最后 1Mb;附加了日志行,所以我想保留最新的条目,而不是最旧的(截断后的文件将始终与此代码相同)。

最佳答案

您不能使用 ftruncate 函数来执行此过程,因为它只接受最终截断大小作为参数并且截断是从头开始执行的。试一试:

// open the file for reading only
$fp = fopen($file,'r');
// place the pointer at END - 125000
fseek($fp,-125000,SEEK_END);
// read data from (END - 125000) to END
$data = fgets($fp,125000);
// close the file handle
fclose($fp);

// overwrite the file content with data
file_put_contents($file,$data);

关于php - 使用 PHP 在末尾截断文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com