我的文件大小为230MB。我想计算该文件的行数。
我尝试了“ Scripting.FileSystemOblect
”,但内存不足。
请帮助。
感谢。
答案 0 :(得分:5)
正常的Windows换行符是CRLF,因此您可以计算LF,并在文件的最后一行之后没有一个的情况下为计数加1。
在真正的VB(即VB5,VB6等)中,您可以使用面向字节的字符串操作来加速许多任务。如果我们可以假设文本文件包含ANSI,那么这很快:
Option Explicit
Private Sub Main()
Const BUFSIZE As Long = 100000
Dim T0 As Single
Dim LfAnsi As String
Dim F As Integer
Dim FileBytes As Long
Dim BytesLeft As Long
Dim Buffer() As Byte
Dim strBuffer As String
Dim BufPos As Long
Dim LineCount As Long
T0 = Timer()
LfAnsi = StrConv(vbLf, vbFromUnicode)
F = FreeFile(0)
Open "big.txt" For Binary Access Read As #F
FileBytes = LOF(F)
ReDim Buffer(BUFSIZE - 1)
BytesLeft = FileBytes
Do Until BytesLeft = 0
If BufPos = 0 Then
If BytesLeft < BUFSIZE Then ReDim Buffer(BytesLeft - 1)
Get #F, , Buffer
strBuffer = Buffer 'Binary copy of bytes.
BytesLeft = BytesLeft - LenB(strBuffer)
BufPos = 1
End If
Do Until BufPos = 0
BufPos = InStrB(BufPos, strBuffer, LfAnsi)
If BufPos > 0 Then
LineCount = LineCount + 1
BufPos = BufPos + 1
End If
Loop
Loop
Close #F
'Add 1 to LineCount if last line of your files do not
'have a trailing CrLf.
MsgBox "Counted " & Format$(LineCount, "#,##0") & " lines in" & vbNewLine _
& Format$(FileBytes, "#,##0") & " bytes of text." & vbNewLine _
& Format$(Timer() - T0, "0.0#") & " seconds."
End Sub
鉴于7,000,000行文件293MB,这里只需0.7秒。但请注意,我没有重新启动以确保在运行该测试时文件未被缓存。没有缓存(即重启后),我希望它只需要5倍。
转换为处理Unicode文本文件非常简单。只需用非B等效项替换B函数,确保将BUFSIZE设置为2的倍数,并搜索vbLf
而不是ANSI LF字节。
答案 1 :(得分:2)
您可以通过将每一行读入同一个变量来实现。没有必要保存所有行:
dim s as string
dim n as integer
open "filename.txt" for input as 1
n = 0
do while not eof(1)
line input #1, s
n = n + 1
loop
这还没有经过测试,自从我做了任何VB6以来已经有一段时间了,但它应该已经接近了。
答案 2 :(得分:2)
对于一个480m二进制文件,1mil + 0xD(vbcr),这需要大约6秒钟
Dim buff() As Byte
Dim hF As Integer
Dim i As Long, n As Long
hF = FreeFile(0)
Open "c:\windows\Installer\2f91fd.msp" For Binary Access Read As #hF
ReDim buff(LOF(hF) - 1)
Get #hF, , buff()
Close #hF
For i = 0 To UBound(buff)
If buff(i) = 13 Then n = n + 1
Next
MsgBox n