fseek()按行而不是字节? [英] fseek() by line, not bytes?
问题描述
我有一个脚本,可以逐行解析大文件.当遇到无法处理的错误时,它将停止,并通知我们已解析的最后一行.
I have a script that parses large files line by line. When it encounters an error that it can't handle, it stops, notifying us of the last line parsed.
这真的是查找文件中特定行的最佳/唯一方法吗? (在我的情况下,fseek()
不可用.)
Is this really the best / only way to seek to a specific line in a file? (fseek()
is not usable in my case.)
<?php
for ($i = 0; $i < 100000; $i++)
fgets($fp); // just discard this
我使用它没有问题,它足够快-感觉有点脏.据我对底层代码的了解,我认为没有更好的方法可以做到这一点.
I don't have a problem using this, it is fast enough - it just feels a bit dirty. From what I know about the underlying code, I don't imagine there is a better way to do this.
推荐答案
查找文件中特定行的简单方法是使用 SplFileObject
类,该类支持查找行号( seek()
)或字节偏移量( fseek()
).
An easy way to seek to a specific line in a file is to use the SplFileObject
class, which supports seeking to a line number (seek()
) or byte offset (fseek()
).
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
在后台,seek()
会执行您的PHP代码(C语言代码除外).
In the background, seek()
just does what your PHP code did (except, in C code).
这篇关于fseek()按行而不是字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!