gpt4 book ai didi

php - 如何观看用 PHP 写入的文件?

转载 作者:IT王子 更新时间:2023-10-29 00:15:13 28 4
gpt4 key购买 nike

我想用 PHP 做 tail 命令之类的 Action , 但是 watch 如何追加到文件中呢?

最佳答案

我不相信有什么神奇的方法可以做到这一点。您只需要不断轮询文件大小并输出任何新数据。这实际上很容易,唯一需要注意的是文件大小和其他统计数据缓存在 php 中。解决方案是在输出任何数据之前调用 clearstatcache()

这是一个快速示例,不包括任何错误处理:

function follow($file)
{
$size = 0;
while (true) {
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}

$fh = fopen($file, "r");
fseek($fh, $size);

while ($d = fgets($fh)) {
echo $d;
}

fclose($fh);
$size = $currentSize;
}
}

follow("file.txt");

关于php - 如何观看用 PHP 写入的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1102229/

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