我试图制作一个脚本来获取文件中的信息。文件中的数据具有以下格式:
#index|info1|info2|info3|info4|#index2|info21|info22|info23|info24
所以我必须直接对文件进行二进制搜索,查找索引并获取其所有信息。例如:
$index = "index2";
Output: index2 info21 info22 info24
我试过了:
$file = "file.txt";
// open the file for reading
$myfile = fopen($file, "r") or die("File cannot be openned");
$indexToSearch = "9780857293039";
$begging = 0;
$end = filesize($file) / sizeof($indexToSearch) - 1;
while($begging <= $end) {
$middle = ($end + $begging) / 2; );
$line = fread($myfile, $middle);
if(strcmp($line,$indexToSearch) == 0) {
echo "found";
break;
} else
if(strcmp($line,$indexToSearch) > 0) {
$end = $middle - 1;
} else {
$begging = $middle + 1;
}
}
fseek($myfile, $middle);
echo "<br><br>FINAL: ".fgets($myfile);