Skip to content

Instantly share code, notes, and snippets.

@midorikocak
Created June 20, 2017 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save midorikocak/37374082930b0dfb444f690ca638e323 to your computer and use it in GitHub Desktop.
Save midorikocak/37374082930b0dfb444f690ca638e323 to your computer and use it in GitHub Desktop.
Google Interview Question (Implement unix tail using file API)
<?php
function tail($filename, $numberOfLines){
$counter = 0;
$handler = fopen($filename, 'r');
$end = filesize($filename);
$start = -1;
$current = $start;
while($current+$end>0 && $counter<$numberOfLines){
fseek($handler, $current, SEEK_END);
$char = fread($handler, 1);
while($char!=="\n" && $current+$end>=0){
$here = $current+$end;
fseek($handler, $current, SEEK_END);
$char = fread($handler, 1);
$current--;
}
if($current!=$start){
if($end+$current+1!=0) {echo fread($handler, $end+$current+1)."\n";}
else {
fseek($handler, 0);
echo fread($handler, $end+$start+1)."\n";
}
$start=$current;
$counter++;
}
}
}
tail("lines.txt", 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment