Rated
Read 36,109 times
Related Categories
Count Lines in File
The code below counts the number of lines in a file. Simply call the CountLines procedure, passing
the file name in its parameter
Function CountLines(ByVal strFilePath As String) As Integer
' 'delcare
variables
Dim fileFile As Integer
Dim intLinesReadCount As Integer
intLinesReadCount = 0
' 'open file
fileFile = FreeFile
If (File_Exists(strFilePath)) Then
Open strFilePath For Input As fileFile
Else
'file doesn't exist
MsgBox "File: " & strFilePath & " hasn't been downloaded
yet. Preprocessing is being aborted.", MB_OK, "File Does Not
Exist"
Count_Lines_In_File = -1
Exit Function
End If
'loop
through file
Dim strBuffer As String
Do While Not EOF(fileFile)
'read line
Input #fileFile, strBuffer
'update count
intLinesReadCount = intLinesReadCount + 1
Loop
'close
file
Close fileFile
'return
value
Count_Lines_In_File = intLinesReadCount
End Function
Function File_Exists(strFilePath As String)
If Dir(strFilePath, vbNormal + vbHidden + vbSystem +
vbReadOnly) = "" Then
File_Exists = False
Else
File_Exists = True
End If
End Function
James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.
Comments
-
Posted by Pamenja on 26 Mar 2005
I used the code provided by James to count the number of lines in a textfile. Looking at my text file in an advanced "notepad" editor it had 3533 lines. The CountLines procedure counted 5043 lines.
... -
Here it is in VB.Net with an error check to see if the file exists, and a check in case reading poops out somewhere mid stream:
[code]
Public Function CountLinesInFile(ByVal strFilePath As Stri...
|