View Full Version : reading a certain line from a .txt
06-04-2007, 01:08 PM
Alright I have a .TXT and I need to read the last and second to last line from the .txt file, how would I go about doing it?
I have been searching on google/wiki/w3/forums/etc. for hours and can't find anything that works.
06-04-2007, 01:49 PM
No code but the basic idea would be:
1. Read the file into an array using file() (http://uk3.php.net/file)
2. Count (http://uk3.php.net/count) the number of elements in the array.
3. Return the element that corresponds with the value of your count, and the value of your count-1.
That should get you started.
06-04-2007, 02:42 PM
Something like (for big files...)
// get the last two lines
$get = 2;
// out container
$out = array_fill ( 1, $get, '' );
// file starting position (feof + last \n)
$pos = -2;
// file to open
$file = 'junk.txt';
// r+ so we can read and write if we need to, just r if reading only
$io = fopen ( $file, 'r+' );
if ( fseek ( $io, $pos--, SEEK_END ) == -1 )
else if ( ( $chr = fgetc ( $io ) ) == "\n" )
$get -= 1;
$out[$get] = $chr . $out[$get];
} while ( $get != 0 );
fclose ( $io );
// just in case it windows rtrim (\r)
$out = array_map ( 'rtrim', $out );
print_r ( $out );
06-04-2007, 05:30 PM
Here's something to look at for contrast/comparison. :)
open (FILE, 'file.txt') || die $!;
@last2lines = (<FILE>)[-2,-1];
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.