| 发表于:2007-07-04 19:15:468楼 得分:0 |
option explicit '功能:以字节方式替换文件内容后输出 '参数:源文件名,输出文件名,查找内容,替换内容 '注意:替换内容是区分大小写的 ' 可以处理任何类型文件,但如果处理的是可执行类二进制文件 ' 有可能造成破坏而不能正常运行 ' '调用示例: ' 将文件 abc.txt 中的 "ab " 字符全部替换为 "12 " ' bytereplace "c:\abc.txt ", "c:\abc2.txt ", "ab ", "12 " ' '代码编写:阿勇 fxy_2002@163.com '日期:2007/07/04 ' sub bytereplace(byval sfile as string, byval ofile as string, fstr as string, rstr as string) dim fbyte() as byte dim fstrbyte() as byte, rstrbyte() as byte fstrbyte = strconv(fstr, vbfromunicode) rstrbyte = strconv(rstr, vbfromunicode) dim l as long l = ubound(fstrbyte) + 1 if l <> ubound(rstrbyte) + 1 then exit sub '替换内容与被替换内容不等长,退出 dim f as integer dim fl as long f = freefile() open sfile for binary as #f fl = lof(f) redim fbyte(fl - 1) get #f, , fbyte close #f dim i as long, j as long dim b as boolean for i = 0 to (fl - 1) - (l - 1) '遍历整个文件字节数组 if fbyte(i) = fstrbyte(0) then '如果与第一个字节匹配,进入循环比较后续字节。 '否则,从下一个字节开始重新匹配 b = true for j = 1 to (l - 1) if fbyte(i + j) <> fstrbyte(j) then b = false exit for end if next if b then '全部字节匹配,替换内容 for j = i to i + (l - 1) fbyte(j) = rstrbyte(j - i) next i = i + (l - 1) '替换内容后,当前指针跳过已替换之内容,处理下一个匹配项 end if end if next f = freefile() open ofile for binary as #f put #f, , fbyte close #f erase fbyte erase fstrbyte erase rstrbyte end sub | | |
|