|
-
Apr 8th, 2006, 05:15 AM
#1
Thread Starter
Frenzied Member
[RESOLVED] Help needed to read text file
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.
-
Apr 8th, 2006, 06:55 AM
#2
Re: Help needed to read text file
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
-
Apr 8th, 2006, 10:18 AM
#3
Re: Help needed to read text file
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
-
Apr 8th, 2006, 11:04 PM
#4
Re: Help needed to read text file
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.
-
Apr 9th, 2006, 05:50 AM
#5
Re: Help needed to read text file
 Originally Posted by Al42
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 say
'The last line is:'
-
Apr 9th, 2006, 05:51 AM
#6
Re: Help needed to read text file
Which would be the correct result.
-
Apr 9th, 2006, 12:02 PM
#7
Thread Starter
Frenzied Member
Re: Help needed to read text file
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|