读取正在更改的文件

发布于 2024-12-03 08:13:54 字数 431 浏览 0 评论 0原文

提供了以下示例代码:

<?php
$handle = fopen("/tmp/test_file/sometestfile", "r");
$contents = '';
while (!feof($handle)) {
    $contents = fread($handle, 10);
    print $contents;
    sleep(1);
}
fclose($handle);
?> 

如果 sometestfile(在我的例子中是一个 txt 文件)在读取循环期间发生更改,为什么 php 程序继续从旧文件中读取? 假设它充满了 1,我将 sometestfile_new 覆盖在它上面,它充满了 2。 我在 Linux 上运行这个,这个 inode 相关吗? 如果在每个循环之后添加 rewind() ,则在覆盖时间点之后将读取新文件。

Provided the following example code:

<?php
$handle = fopen("/tmp/test_file/sometestfile", "r");
$contents = '';
while (!feof($handle)) {
    $contents = fread($handle, 10);
    print $contents;
    sleep(1);
}
fclose($handle);
?> 

If sometestfile, which is a txt file in my case, changes during the read loop, why is the php program continuing to read from the old file?
Say it is full of 1's and I cat sometestfile_new over it which is full of 2's.
I am running this on Linux, is this inode related?
If rewind() is added after each loop, the new file will be read instead, after the overwrite point in time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉栀 2024-12-10 08:13:54

来自 php.net

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() 绑定一个命名的由 filename 指定的资源到流。

fopen() 一旦被调用,它就会“缓存”文件,并将在您提到的方法中输出,例如您的 $contents = fread($handle, 10);

您可以删除该文件,它仍然会读取该资源,直到完成该文件 !feof($handle)

您不能使用 fopen() 执行任何其他操作,您只是无法重读源代码继续打印它。

from php.net

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() binds a named resource, specified by filename, to a stream.

the fopen() as soon as it's called it "caches" the file and will output in the method you mention, example is your $contents = fread($handle, 10);

You can delete the file and it will still read that resource until it finishes the file !feof($handle)

You cannot do anything else with fopen(), you just can't reread the source and continue to print it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文