Last active
December 19, 2015 21:48
-
-
Save mamchenkov/6022397 to your computer and use it in GitHub Desktop.
Read file line-by-line from given byte offset. Handy for re-processing large logs files.
This file contains hidden or 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 | |
/** | |
* Read file line-by-line from given byte offset. | |
* Handy for re-processing large logs files. | |
*/ | |
// Filename to use for temporary data | |
define('DATA_FILE', 'data.log'); | |
// Create the data file on the fly | |
$data = <<<EOF | |
one | |
line two | |
line three | |
another line number four | |
five | |
six six six | |
seven eleven | |
EOF; | |
if (!file_put_contents(DATA_FILE, $data)) { | |
print "Failed to write sample data to file\n"; | |
exit(1); | |
} | |
// Open file | |
$fh = fopen(DATA_FILE, 'r'); | |
if (!$fh) { | |
print "Failed to open file for reading\n"; | |
exit(1); | |
} | |
// Move to specified position, or stay on top | |
$from = empty($argv[1]) ? 0 : $argv[1]; | |
fseek($fh, $from); | |
// Read line-by-line from given position | |
while (($line = fgets($fh)) !== false) { | |
$line = trim($line); | |
$pos = ftell($fh); | |
$pos = $pos - strlen($line) - 1; // 1 is for line break | |
print "Position: $pos, Line: $line\n"; | |
} | |
fclose($fh); | |
// Remove data file | |
unlink(DATA_FILE); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment