此文件比对基于二进制,最大特点,使用了long型数组,采用32系统最擅长的数据类型进行比对,速度明显快于byte数组。
option explicit
private cencelcopy as boolean
private declare sub copymemory lib “kernel32” alias “rtlmovememory” (pdest as any, psource as any, byval dwlength as long)
private sub command1_click()
dim pos as long
command1.enabled = false
command2.enabled = true
pos = compfile(text1.text, text2.text)
command1.enabled = true
command2.enabled = false
select case pos
case -2
msgbox “file not exist”
case -1
msgbox “user cancel”
case 1
msgbox “len error”
case 0
msgbox “compare ok”
case else
msgbox “compare fail in ” & pos
end select
end sub
private function compfile(file1 as string, file2 as string) as long
dim i as long, k as long
dim pos as long, eventsnum as long
dim fileno as integer, fileno1 as integer, filelast() as byte, filelast1() as byte
dim alllen as long, onelen as integer, buflen as long
long型比对
dim buf() as long, buf1() as long
buflen = 8192
onelen = 4
byte型比对
dim buf() as byte, buf1() as byte
buflen = 25600
onelen = 1
dim t as single
t = timer – 0.1 减 0.1 是防止测速运算的除零错误,同时也能消除点缓存对测速的影响
if dir(file1) = “” or dir(file2) = “” or file1 = “” or file2 = “” then compfile = -2: exit function
cencelcopy = false
fileno = freefile
open file1 for binary access read as #fileno
alllen = lof(fileno)
pos = 1
eventsnum = 1
fileno1 = freefile
open file2 for binary access read as #fileno1
if lof(fileno1) <> alllen then compfile = 1: goto ext
redim buf(buflen – 1)
redim buf1(buflen – 1)
do while pos + buflen * onelen – 1 <= alllen
get #fileno, , buf
get #fileno1, , buf1
for k = 0 to ubound(buf)
if buf(k) <> buf1(k) then
compfile = pos + k * onelen
redim filelast(3) 若想精确定位不同处在哪个字节,可加上这段
redim filelast1(3)
copymemory filelast(0), buf(k), 4
copymemory filelast1(0), buf1(k), 4
for i = 0 to 3
if filelast(i) <> filelast1(i) then exit for
next
compfile = compfile + i
goto ext
end if
next
if eventsnum mod 10 = 0 then
cls
print pos, round(timer – t, 2), round((pos / (timer – t)) / 1024, 2) & “kb/s”
doevents
if cencelcopy then compfile = -1: goto ext
end if
eventsnum = eventsnum + 1
pos = pos + buflen * onelen
loop
redim filelast(alllen – pos)
redim filelast1(alllen – pos)
get #fileno, , filelast
get #fileno1, , filelast1
for k = 0 to ubound(filelast)
if filelast(k) <> filelast1(k) then compfile = pos + k: goto ext
next
pos = alllen
ext:
close #fileno1
close #fileno
cencelcopy = true
cls
print pos, round(timer – t, 2), round((pos / (timer – t)) / 1024, 2) & “kb/s”
end function
private sub command2_click()
cencelcopy = true
end sub
private sub form_load()
cencelcopy = true
command1.enabled = true
command2.enabled = false
end sub
private sub form_unload(cancel as integer)
if cencelcopy = false then
cencelcopy = true
cancel = 1
end if
end sub