如果线的长度是文字和变量,你可以不知道哪个线#97;唯一使它成为第97位的是前面有96行。
所以,你需要阅读整个文件到这一点(这是SplFileObject做什么):
$fp = fopen("keywords.txt", "r");
while($line--)
{
if (feof($fp))
// ERROR: line does not exist
$text = fgets($fp, 1024); // 1024 = max length of one line
}
fclose($fp);
但如果你能在每行之前存储的行号,即该文件是
最有可能的
- start with s1 = 0 and s2 = file length
- read a keyword and line number at seek position s3 = (s1+s2)/2 (*)
- if line number is less than desired, s1 = s3; else s2 = s3; and repeat previous step.
- if line number is the one desired, strip the number from the text and you get the keyword.
(*),因为该行:
...
95 abbagnale
96 abbatangelo
97 abbatantuono
98 ...
那么你可以实现一种二进制搜索不会在s#正好开始,你需要与fgets:一个摆脱了伪半关键字,第二读取的行号。当你“关闭”时,阅读一个更大的块并将其分成多行会更快。例如,您寻找第170135行并在第170180行读取:您最好做的是将搜索位置倒回一千字节,读取一千字节的数据,然后在那里寻找170135。
或者,如果各行的长度不太相同,则可能需要存储固定大小的行(这里“#”实际上应该是空格,并且在行长度中需要对行进行计数终止子,\ n或\ r \ n)的:
abbagnale#########
abbatangelo#######
abbatantuono######
,然后说每个关键字是32个字节,
$fp = fopen("keywords.txt", "r");
fseek($fp, 97 * 32, SEEK_SET);
$text = trim(fgets($fp, 32));
fclose($fp);
会或多或少瞬时的。
如果文件位于远程服务器上,您仍然需要下载整个文件(直到所需的行),通过在远程服务器上放置一个“scanner”脚本可以更好地服务运行搜索。然后你可以运行
$text = file_get_contents("http://www.mysite.com/keywords.php?line=97");
并以毫秒为单位获得你的行。
你为什么不使用数据库来实现呢? – 2013-02-18 11:16:58