...

View Full Version : reading a certain line from a .txt



TexasMd91
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.

Pennimus
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.

printf
06-04-2007, 02:42 PM
Something like (for big files...)


<?php

// 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+' );

do
{
if ( fseek ( $io, $pos--, SEEK_END ) == -1 )
{
break;
}
else if ( ( $chr = fgetc ( $io ) ) == "\n" )
{
$get -= 1;
}
else
{
$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 );

?>

FishMonger
06-04-2007, 05:30 PM
Here's something to look at for contrast/comparison. :)

#!/usr/bin/perl

open (FILE, 'file.txt') || die $!;

@last2lines = (<FILE>)[-2,-1];

print @last2lines;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum