读取正在更改的文件
提供了以下示例代码:
<?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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 php.net
fopen()
绑定一个命名的由filename
指定的资源到流。fopen()
一旦被调用,它就会“缓存”文件,并将在您提到的方法中输出,例如您的$contents = fread($handle, 10);
您可以删除该文件,它仍然会读取该资源,直到完成该文件
!feof($handle)
您不能使用
fopen()
执行任何其他操作,您只是无法重读源代码继续打印它。from php.net
fopen()
binds a named resource, specified byfilename
, 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.