Open text file from the from the end backwards

S

Stupid48

I'm trying to do a simple task but can't seem to find a solution. How
do I read lines from a text file backwards.

i.e. I want to select the last 20 lines of a text file and display them
in order starting with the last line first.....

Any assistance would be greatly appreciated....

Thanks, Chris
 
T

Tom Leylan

Unless they've changed something in the last decade :)

You're probably opening the textfile as a "stream of data" in which case you
must read forward. That leaves you with one of two solutions (in my mind.)
If the data isn't going to change as you are reading it you can make two
passes. The first one is to count how many lines you have, then you rewind
and skip as many lines as needed until you get to the point where 20 remain.
Append those to a collection and reverse the order just prior to using it.

The other method permits you to make a single pass but it means you will
store each line into a collection that contains a maximum of 20 items. Each
time you are about to store a new one you see if there are 20 and if so
delete the earliest one. At the end you will have a maximum of 20 items in
the collection. Reverse the order as above.

There is actually a third method. Simply read ever line into the
collection, reverse the order and limit the number of items you display.

Tom
 
S

Stupid48

Thanks for the reply.....Yah, you'd think I could figure this out. I
don't know how to reverse the order of a collection. I guess that's
the problem. I'll keep searching.

Thanks again...
 
S

Stupid48

Got it. Just created an arraylist and then looped through the index
backwards. Duh

Thanks again...
 
O

\(O\)enone

Stupid48 said:
i.e. I want to select the last 20 lines of a text file and display
them in order starting with the last line first.....

If you're using VS2005, you can use the System.IO.File.ReadAllLines()
function to read the file into a String array, with one array element for
each line in the file. Then just loop from the last string array element
backwards to display each of the lines of text.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top