VB 二进制块读写类模块应用实例 包括一个文件拷贝和一个文件二进制比较的例子
VB 二进制块读写类模块应用实例 包括一个文件拷贝和一个文件二进制比较的例子,VB 二进制块读写类模块应用实例,包括一个文件拷贝和一个文件二进制比较的例子。
文件拷贝实例:(Text1存放源文件位置,Text2存放目标文件位置)------------------------------------------------------------------------
Private Sub Command3_Click()Const BUFFER_SIZE = 40960 * 2 '规定缓冲区大小Dim nActual As LongDim aBuf(0 To BUFFER_SIZE - 1) As Byte '分配缓冲区Dim tmr As Single '计时变量Dim lFileLen As Long '纪录文件长度Dim iFileNum As Integer '记录文件号Dim k As Long
tmr = Timer
If Not m_cFileRead.OpenBinary(Text1.Text) Then MsgBox "打开文件失败!" & Text1.TextIf Not m_cFileWrite.OpenBinary(Text2.Text) Then MsgBox "打开文件失败!" & Text2.Text
'记下文件长度和打开文件所用的文件号,是为了优化性能。lFileLen = m_cFileRead.FileLengthiFileNum = m_cFileRead.FileNumber
k = 0Do k = k + 1 If k = 10 Then k = 0 'pb1是进度条控件。 pb1.Value = 100 * (Seek(iFileNum) / lFileLen) '显示百分比 DoEvents End If '读块,传给它缓冲区指针和期望读取的字节数,返回实际读取的字节数, nActual = m_cFileRead.ReadBlock(VarPtr(aBuf(0)), BUFFER_SIZE) '写块,传给它缓冲区指针和期望写入的字节数。 m_cFileWrite.WriteBlock VarPtr(aBuf(0)), nActualLoop Until nActual < BUFFER_SIZE '当实际读取字节数小于缓冲区大小的时候,就不需要再读啦,已读完啦
m_cFileRead.CloseFile '关文件m_cFileWrite.CloseFile
MsgBox "OK! total time:" & Timer - tmrEnd Sub
---------------------------------------------------------------------------------------------------------------------------------------
二进制文件比较实例(Text1存放第一个文件的位置,Text2存放第二个文件的位置)----------------------------
Private Sub Command2_Click()
Const BUFFER_SIZE As Long = 4096 * 2 '规定缓冲区大小Dim cfRead1 As New CFileReadDim cfread2 As New CFileReadDim aBuf1(0 To BUFFER_SIZE - 1) As Byte '分配缓冲区Dim aBuf2(0 To BUFFER_SIZE - 1) As ByteDim nActual As LongDim i As Long, lCurPos As LongDim tmr As SingleDim k As Long
tmr = Timer
If Not cfRead1.OpenBinary(Text1.Text) Then MsgBox "open file failed:" & Text1.TextIf Not cfread2.OpenBinary(Text2.Text) Then MsgBox "open file failed:" & Text2.Text
If cfRead1.FileLength <> cfread2.FileLength Then MsgBox "文件不一样长"
lCurPos = 1 '当前待比较字节的位置,虚拟位置,不同于文件的读写指针。k = 0Do '读块,传给它缓冲区指针和期望读取的字节数,返回实际读取的字节数, nActual = cfRead1.ReadBlock(VarPtr(aBuf1(0)), BUFFER_SIZE) '读第2个文件的数据块 nActual = cfread2.ReadBlock(VarPtr(aBuf2(0)), BUFFER_SIZE) For i = 0 To nActual - 1 '比较缓冲区 If aBuf1(i) <> aBuf2(i) Then MsgBox "不同,位置:" & lCurPos: Exit Do lCurPos = lCurPos + 1 '移到下一个待比较字节的位置 Next i k = k + 1 If k = 100 Then k = 0 Cls Print Timer - tmr, " ", (Seek(cfRead1.FileNumber) / 1024) / (Timer - tmr) & " KB/s" End IfLoop Until nActual < BUFFER_SIZE
cfRead1.CloseFile '关文件cfread2.CloseFile
MsgBox "OK! " & Timer - tmr
End Sub---------------------------------------------------------------------------------------------------------------------------------------