使用 vbscript 修改文件的前两个字节 [英] Modify first two bytes of a file using vbscript

查看:32
本文介绍了使用 vbscript 修改文件的前两个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含以下内容的 4 字节文件

Suppose we have a 4-byte file with the following contents

00 00 00 00

我要修改前两个字节说

FF AA 00 00

我怎样才能用 vbscript 做到这一点?使用 vbscript 的二进制 IO 参考也不错.

How can I accomplish this with vbscript? A reference for binary IO using vbscript would also be nice.

推荐答案

你可以看看这个问题的答案中的例子:在VBscript中读写二进制文件

You could take a look at the example in the answer to this question: Read and write binary file in VBscript

我不知道这在实践中的效果如何(mid 函数可能会破坏结果),但使用以下代码似乎对我有用:

I don't know how well this will work in practice (the mid function may mangle the results), but it seems to work here for me using the following code:

Option Explicit
Dim data

data = readBinary("C:\test.file")
' CHR(255) = FF, CHR(170) = AA
data = Chr(255)&Chr(170) & Mid(data, 3, Len(data) - 2)
writeBinary data,"C:\newtest.file"

Function readBinary(path)
    Dim a, fso, file, i, ts
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.getFile(path)
    If isNull(file) Then
        wscript.echo "File not found: " & path
        Exit Function
    End If
    Set ts = file.OpenAsTextStream()
    a = makeArray(file.size)
    i = 0
    While Not ts.atEndOfStream
       a(i) = ts.read(1)
       i = i + 1
    Wend
    ts.close
    readBinary = Join(a,"")
 End Function


 Sub writeBinary(bstr, path)
     Dim fso, ts
     Set fso = CreateObject("Scripting.FileSystemObject")
     On Error Resume Next
     Set ts = fso.createTextFile(path)
     If Err.number <> 0 Then
        wscript.echo Err.message
        Exit Sub
     End If
     On Error GoTo 0
     ts.Write(bstr)
     ts.Close
 End Sub

Function makeArray(n)
    Dim s
    s = Space(n)
    makeArray = Split(s," ")
End Function

这篇关于使用 vbscript 修改文件的前两个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆