Log inUsernamePassword
Log me on automatically each visit    
Register
Register
Log in to check your private messages
Log in to check your private messages
Visual Basic Forum for Visual Basic Programmers VB Forum Index » Knowledge Base

Post new topic   Reply to topic
Quickly estimate the total number of lines in a file
View previous topic :: View next topic  
Author Message
Avis
Junior Poster


Joined: 07 Oct 2003
Posts: 510
Location: India

PostPosted: Oct 8th, 2003 06:12 AM    Post subject: Quickly estimate the total number of lines in a file Reply with quote

If you want to find out the total number of lines in a file, you can simply do something like this :

Code:
Private Function getLineCount(ByVal strFilePath As String) As Long
    Open strFilePath For Binary As #1
        Dim strBuff As String: strBuff = Space(Lof(1))
        Get #1, , strBuff
        getLineCount = UBound(Split(strBuff, vbCrLf))
    Close #1
End Function

But if you're dealing with very large text files, then something like that could take a very long time to complete.
So why not get an estimate on the number of lines ?

Code:
Private Function getLineCount(ByVal strFilePath As String) As Long
    Dim i As Long, lngTotalLengthSoFar As Long, lngAverageLength As Long
    Open strFilePath For Input As #1
        Dim strBuff As String:  strBuff = Space(LOF(1))
        Dim strBuff2 As String: strBuff2 = vbNullString
        For i = 0 To 49
            Line Input #1, strBuff2
            lngTotalLengthSoFar = lngTotalLengthSoFar + Len(strBuff2)
        Next
        lngAverageLength = lngTotalLengthSoFar / 50
        getLineCount = LOF(1) / lngAverageLength
    Close #1
End Function


The above code will take the first 50 lines, and estimate from that, the total number of lines in the file.
As with all statistical or analysis operations, the larger the source dataset the more accurate your results will be, so increasing the sample size from 50 to 100 or 200 would, on average, provide you with a more accurate result.

At the same time, if you don't require brilliant accuracy, or know that each line is a very similar length and want to get the job done quick, then one could reduce the sample from 50 to 10 or 20 etc.
Back to top
View user's profile Send private message Send e-mail Visit poster's website Yahoo Messenger MSN Messenger ICQ Number
Display posts from previous:   
Post new topic   Reply to topic    Visual Basic Forum for Visual Basic Programmers VB Forum Index » Knowledge Base All times are GMT - 5 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Visual Basic Forum runs phpBB | Forum Template © iOptional
VB Resources | SSL | Visual Basic