Search code examples
scriptingvbscript

Function to count number of lines in a text file


Need a function that will accept a filename as parameter and then return the number of lines in that file.

Should be take under 30 seconds to get the count of a 10 million line file.

Currently have something along the lines of - but it is too slow with large files:

Dim objFSO, strTextFile, strData, arrLines, LineCount
CONST ForReading = 1

'name of the text file
strTextFile = "sample.txt"

'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll

'Split by lines, put into an array
arrLines = Split(strData,vbCrLf)

'Use UBound to count the lines
LineCount = UBound(arrLines) + 1

wscript.echo LineCount

'Cleanup
Set objFSO = Nothing

Solution

  • The only alternative I see is to read the lines one by one (EDIT: or even just skip them one by one) instead of reading the whole file at once. Unfortunately I can't test which is faster right now. I imagine skipping is quicker.

    Dim objFSO, txsInput, strTemp, arrLines
    Const ForReading = 1
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    strTextFile = "sample.txt"
    txsInput = objFSO.OpenTextFile(strTextFile, ForReading)
    
    'Skip lines one by one 
    Do While txsInput.AtEndOfStream <> True
        txsInput.SkipLine ' or strTemp = txsInput.ReadLine
    Loop
    
    wscript.echo txsInput.Line-1 ' Returns the number of lines
    
    'Cleanup
    Set objFSO = Nothing
    

    Incidentally, I took the liberty of removing some of your 'comments. In terms of good practice, they were superfluous and didn't really add any explanatory value, especially when they basically repeated the method names themselves, e.g.

    'Create a File System Object
    ... CreateObject("Scripting.FileSystemObject")