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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to read file from the end to beginning ?

Status
Not open for further replies.

andimue

Programmer
Jun 29, 2001
18
DE
Hi,
I need to manipulate some list-files with perl under Sun Solaris 2.8, which I get from somebody else. Therefor I need to read the file from the end towards the beginning of the file.
I think, there should be a way to do this, but I didnt find out how to .
Maybe someone could "open my eyes".
Thx

andi
 
maybe this is somewhere close to what you need.

Code:
#!/usr/local/bin/perl
# there are a few *nix OS approaches to this, but....
# staying completely within perl
open(FILE, &quot;<lines.txt&quot;) or die &quot;Failed to open, $!&quot;;
@lines = <FILE>;
close FILE;
foreach (reverse(@lines))	{ print; }

HTH If you are new to Tek-Tips, please use descriptive titles, check the FAQs,
and beware the evil typo.
 
Hi goBoating,
first of all thanks for your reply. I have 2 more questions :
1. you talked about approaches to read file reverse under Sun Solaris. Can you tell me how ?
2. I dont know how big the file can be. In your solution, isn't the whole file read into memory ? I am afraid of running out of memory while working with a really big file.

cu
andimue
 
with the OS,

@lines = `cat -n file_name | sort -r`;

This gets the lines of the file in the reverse order, but it also unfortunately prepends a number to the front of each line and reads the entire file.

I guess you could concievably open the file, seek to the end and start incrimentally backing up into the file. I don't see why this could not be done, but, I think it would be tedious and require a fair amount of processor time, so it might not be better that reading the entire file in.

My first attempt would be to read the entire file in and see if I had a performance problem. Then, once the problem was real, I would see about reading it line by line from the tail end first.

This would be an interesting exercise.... backing into a file. I can't get to it now, but, I might have to come back and play with that puzzle.

Good Luck If you are new to Tek-Tips, please use descriptive titles, check the FAQs,
and beware the evil typo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top