Search code examples
vbscriptbinaryfiles

Read File byte after byte in vbscript


I am looking for a way to read a big binary file using VBScript (big - 1 GB). I can't read it directly with ReadAll function because the file is too big, so I am looking for a way to read it in a loop, like in C. So I want to read X bytes, process them (I don't need the full file to do my stuff), then read next 10 and over again.

The problem is that I can't find a way to do that, I know how to start reading from offset, but can't find a way to read X bytes, there are only ReadAll and ReadLine functions.

Is there a way to read X bytes?


Solution

  • When in doubt, read the documentation:

    Read Method

    Reads a specified number of characters from a TextStream file and returns the resulting string.

    Syntax

    object.Read(characters)
    

    Arguments

    • object
      Required. Always the name of a TextStream object.
    • characters
      Required. Number of characters you want to read from the file.
    filename = "C:\path\to\your.file"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f   = fso.OpenTextFile(filename)
    
    Do Until f.AtEndOfStream
        buf = f.Read(10)
        '...
    Loop
    
    f.Close
    

    Note, however, that the Read() method doesn't read bytes per se, but characters. Which is roughly the same as long as you open the file in ANSI mode (the default).