Hi all,
I need to read the last line alone from a text file and display it to user.
Please help me!
Thanks in advance.
Printable View
Hi all,
I need to read the last line alone from a text file and display it to user.
Please help me!
Thanks in advance.
This is a solution, it is fine if the textfile is not huge, i'm sure someone will post a more effecient solution...
VB Code:
Dim strBuffer$ Dim strLine$ Dim strLineArray$() Dim strLastLine$ Open "c:\t.txt" For Input As #1 While Not EOF(1) Line Input #1, strLine strBuffer = strBuffer & vbCrLf & strLine Wend Close #1 strLineArray = Split(strBuffer, vbCrLf) strLastLine = strLineArray(UBound(strLineArray)) MsgBox "the last line is: " & strLastLine
Can't remember if this is quite right, but something along these lines would be a lot quicker:VB Code:
Dim ff As Long, all As String ff = FreeFile() Open filename for Binary Lock Write As #ff all = Space(LOF(ff)) Get #ff, , all Close #ff Dim lastLine as String lastLine = Mid$(all, InStrRev(all, vbNewLine), Len(all)) MsgBox "Last line is: " & lastLine
The last character may be vbNewLine. If the text from that point is "", test again starting at the last point.
BTW, Mid$(string, start) reads to the end of the string.
if the last char is a new line then post #3 will sayQuote:
Originally Posted by Al42
'The last line is:'
Which would be the correct result.
Hi,
I found another way to solve this problem. Here is the code:VB Code:
Public Function fnReadLastLine(strFileName As String) 'You can call this function as: 'Call fnReadLastLine("C:\a12.txt") Dim fPos As Long, LastLine As String, aByte As Byte Dim testCRLF As String * 2 Const LF = 10 On Error GoTo fnReadLastLine_Error Open strFileName For Binary As #1 fPos = LOF(1) + 1 Do fPos = fPos - 2 Seek #1, fPos Get #1, , testCRLF Loop While testCRLF = vbCrLf Do fPos = fPos - 1 Seek #1, fPos Get #1, , aByte Loop Until aByte = LF Line Input #1, LastLine Close #1 MsgBox Trim$(LastLine) ExitHere: On Error GoTo 0 Exit Function fnReadLastLine_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure fnReadLastLine of Module Module1" End Function