Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get last line of text file.

Status
Not open for further replies.

thenewa2x

Programmer
Dec 10, 2002
349
US
How do you get the last line of a CSV file with out reading the whole file? The CSV file is tabe delimited.

---------------------------------------
 
If it is Tab delimited, then it is by definition not a CSV file. To answer your question however, I don't believe it is possible through native functions.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Ok thx. I found an alternative way but I think its slow:

Code:
$last_line = "";

while ( ( $line = fgets( $fp ) ) )
    $last_line = $line;

Anyway to improve this?

---------------------------------------
 
Use the file() function < to read the whole file into an array.
Code:
<?php
$lines = file('youfilenamehere');
$last_line = $lines[count($lines)-1];
?>
Ken
 
I don't like using file() unless I know for a fact that the file is not all that large. Loading a sufficiently large file into memory can cause your script to exceed memory limits and be shut down.

You might use filesize() to figure out how long the file is.

Then you might pick a reasonable number of bytes that no line in the file will exceed, and use fseek() to position the file pointer that reasonable distance back from the end of the file.

Then read to the last line.

You'd at least not have to loop through a long file.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Are you running PHP on a unix-like OS? If so, you might look at the system command [tt]wc[/tt], which can tell you things about your file that might make the above more efficient.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
If you're using UNIX or Linux or any OS that has a UNIX like tail command, then the command
Code:
tail -1 yourfilehere
will give you the last line.

Ken
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top