Read last line in a file

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
At the moment I am opening a file in sequential mode, reading in each line
until I get the match with the string "Totals" which is the last line in the
file and then extracting the number of records in the file which is one of
the totals on the last line. The files are quite big, so I was wondering if
there was a better way, any ideas?
Thanks
 
In
Peter Clancy said:
Hi,
At the moment I am opening a file in sequential mode, reading in each
line until I get the match with the string "Totals" which is the last
line in the file and then extracting the number of records in the
file which is one of the totals on the last line. The files are quite
big, so I was wondering if there was a better way, any ideas?
Thanks

If you have some sense of the maximum length of the last line, then you
can open the file in binary mode, read that many bytes into a buffer,
and then parse the line out of that buffer. For example:

'----- start of code -----
Dim intFileNo As Integer
Dim lngLen As Long
Dim strBuffer As String

intFileNo = FreeFile()
Open "C:\Your Path\YourFile.txt" For Binary As #intFileNo

' Read the last 255 bytes from the file.
lngLen = LOF(intFileNo)
strBuffer = String(255, " ")
Get #intFileNo, lngLen - 254, strBuffer

Close intFileNo

' For this example, we'll just print the buffer's contents.
' Normally, you'd parse out the totals you want.
Debug.Print strBuffer
'----- end of code -----

Code along those lines should work so long as the files aren't more than
2GB in size. Depending on the encoding scheme for the file, you may
possibly have to do some translation of the bytes you read into the
buffer.
 
That did it
Thank you

Dirk Goldgar said:
In

If you have some sense of the maximum length of the last line, then you
can open the file in binary mode, read that many bytes into a buffer,
and then parse the line out of that buffer. For example:

'----- start of code -----
Dim intFileNo As Integer
Dim lngLen As Long
Dim strBuffer As String

intFileNo = FreeFile()
Open "C:\Your Path\YourFile.txt" For Binary As #intFileNo

' Read the last 255 bytes from the file.
lngLen = LOF(intFileNo)
strBuffer = String(255, " ")
Get #intFileNo, lngLen - 254, strBuffer

Close intFileNo

' For this example, we'll just print the buffer's contents.
' Normally, you'd parse out the totals you want.
Debug.Print strBuffer
'----- end of code -----

Code along those lines should work so long as the files aren't more than
2GB in size. Depending on the encoding scheme for the file, you may
possibly have to do some translation of the bytes you read into the
buffer.

--
Dirk Goldgar, MS Access MVP
www.datagnostics.com

(please reply to the newsgroup)
 
Back
Top