从动态文本文件中提取_基本 PHP 问题
我正在尝试从 txt 文件中提取内容。该文件是动态的,因为每次执行循环时数据都会不断追加到该文件中。 在这个循环中,有我从文件中提取内容的逻辑,如下所示...
$length = filesize($filename);
fseek($fd,$previousLength);
$contents = fread($fd,(($length - $previousLength)));
$previousLength = $length;
即,我试图仅读取在最后一个循环中附加的数据...而不是先前写入的数据。 示例...每次运行循环时,txt都会添加1..即考虑
114134, 144, 1443, 1433 ...
(n of these written every once in loop ) ...
如果我读取n个值,比如说
114134, 144 ...
在第一个循环中...
下一次,我只需要读取
1443, 1443 and NOT 114134, 144 ....
fread() 在这里惨败,而 fseek 则不会'没有帮助(参考我上面的代码)...
我不知道为什么!!需要尽快帮助..
谢谢
I am trying to extract contents from a txt file. This file is dynamic because data keeps appending to it everytime the loop is executed.
Inside this loop rests my logic for extracting contents from file, as follows...
$length = filesize($filename);
fseek($fd,$previousLength);
$contents = fread($fd,(($length - $previousLength)));
$previousLength = $length;
i.e, I AM trying to read only the data that got appended, in the last loop ... and not the data that was previously written.
EXAMPLE... A txt adds ONE everytime a loop is run.. i.e consider
114134, 144, 1443, 1433 ...
(n of these written every once in loop ) ...
If I read n values , say
114134, 144 ...
in the first loop ...
next time, I need to read only
1443, 1443 and NOT 114134, 144 ....
fread() fails miserably here ,and fseek doesn't help ( ref. my code above) ...
I DON"T KNOW WHY !! help needed asap ..
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您以附加模式打开文件,则 fseek 的手册页说:
如果您以追加(a 或 a+)模式打开文件,则无论文件位置如何,写入文件的任何数据都将始终被追加,并且调用 fseek() 的结果将是未定义的。
以下代码有一些修改。我在长度方面遇到了一些问题 - fread 确实需要它,但我决定使用 fgets 来避免它。这将在换行符处停止,但具有读取文件的全部剩余内容的便利功能。可能有更好的方法来做到这一点,但这确实有效。
If you have opened the file in append mode then the man page for fseek says:
If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.
The following code has a few modifications. I had a few problems with the length - fread does require it, but i decided to use fgets to avoid it. This would stop on newline characters but has the handy feature of reading the entire remaining contents of the file otherwise. There may be a better way of doing this, but this does work.
不确定我是否正确,但是您正在从要附加到同一循环中的文件中读取数据?
您写入的所有单独行的数据是否都添加到文件中?您可以查看 file() 命令,它会将每一行读入数组中...然后您可以通过计算之前情况下的行数,然后计算之后情况下的行数来 array_slice() 从数组中取出正确的行。
Not sure if I got this right, but you're reading data from a file that you're appending in the same loop?
Is the data that you write all seperate lines added to the file? You can look at the file() command instead, it reads every line into an array... You can then array_slice() the right lines out of the array by counting lines in before situation, then the after situation.