我用二进制文件读写的方法做了一个文件分割合并软件,但是使用了一段时间之后,发现合并之后的文件与原文件大小不一样,起初大约有4个字节的出入,经过改进,如下:
option base 1
文件分割部分:
Dim part As Integer
Dim filelens As Long
Dim temp() As Byte '保存数据的数组
Dim i As Integer
Dim timeused As Long
Dim leftPart As Long '最后一份文件的大小
'========================================
part = Val(txtpart.Text) '文件分割份数
Open txtsoc1.Text For Binary Access Read As 100
ReDim temp(filelens / part) As Byte
Me.MousePointer = vbHourglass
For i = 1 To part - 1
Open txtobj1.Text & i For Binary As i
Get 100, , temp
Put i, , temp
Close i
Next
ReDim temp(leftPart) As Byte
Open txtobj1.Text & part For Binary As part
Get 100, , temp
Put part, , temp
Close part
Close 100
文件合并部分:
Dim arr() As Byte
Dim lens As Integer '路径的主要信息的长度
Dim filesoc As String '所有待合并文件路径的相同部分
Dim filelens As Long ' 每份待合并文件的大小
Dim totalpart As Integer '总份数
Dim filepath As String '待合并文件路径
Dim i As Integer
Dim pos As Long '文件写入位点
Dim timeused As Long
Open Text2.Text For Binary As 100 '目标文件,保存位置
'Debug.Print Text2.Text
Me.MousePointer = 11
For i = 1 To totalpart
filepath = filesoc & i
filelens = FileLen(filepath)
ReDim arr(filelens) As Byte
'Debug.Print UBound(arr)
Open filepath For Binary As i
Get i, , arr
Put 100, , arr
Close i
Next
Close 100
代码中红色部分是后来改进的,这样改了之后,误差降低了,大约会有一个字节的出入,但是,我再也找不出这一个字节到底到哪去了或从哪里多出来了。
请各位高手不吝赐教!!
上面那两个都用到了API函数。
我重新分析了一下我自己的代码,终于发现问题之所在了。改正后的代码如下:
option base 1
‘=======文件分割部分==========
On Error GoTo err_handle
Dim part As Integer
Dim filelens As Long
Dim temp() As Byte '保存数据
Dim i As Integer
Dim timeused As Long
Dim leftPart As Long '最后一份文件的大小
Dim eachpart As Long '每份文件大小(除最后一份)filelens = FileLen(txtsoc1.Text)
eachpart = (filelens - (filelens Mod part)) / part '由于源文件大小有可能不能被part整除,所以要去掉多余的部分
Open txtsoc1.Text For Binary Access Read As 100
ReDim temp(eachpart) As Byte
Me.MousePointer = vbHourglass
For i = 1 To part - 1
Open txtobj1.Text & i For Binary As i
Get 100, , temp
Put i, , temp
Close i
Next
leftPart = eachpart + (filelens Mod part)'最后一份文件大小为:不能整除的部分加上平均每份的大小
Debug.Print filelens, leftPart, (part - 1) * (filelens / part)
ReDim temp(leftPart) As Byte
Open txtobj1.Text & part For Binary As part
Get 100, , temp
Put part, , temp
Close part
Close 100
‘=============文件合并部分=========
Open Text2.Text For Binary As 100 '目标文件,保存位置
'Debug.Print Text2.Text
Me.MousePointer = 11
For i = 1 To totalpart
filepath = filesoc & i
filelens = FileLen(filepath)
ReDim arr(filelens) As Byte
'Debug.Print UBound(arr)
Open filepath For Binary As i
Get i, , arr
Put 100, , arr
Close i
Next
Close 100
注意以上红色部分就是改进的代码。
虽然文件读写可以像版主说的那样用API 来实现,但我不喜欢用API,非到必要时,尽量少用。当然少了某些API,功能会受到限制。 作者:
Nothing 时间: 2006-5-4 15:08