Created
June 20, 2017 13:34
-
-
Save midorikocak/37374082930b0dfb444f690ca638e323 to your computer and use it in GitHub Desktop.
Google Interview Question (Implement unix tail using file API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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