WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Binary Functions

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

How to Use Binary Functions to Search and Replace

Keywords: 

Question:

Up to now I do not know how to replace strings within a binary buffer, strings that might appear at any (!) offset within the buffer. A function like "BinaryReplace()" that automatically adjusts the buffer size (similar to "StrReplace()") seems not to exist.

I assume that "StrReplace()" is not capable of modifying the contents of a buffer.

I tried to read a file into a binary buffer; then I copied the file into a string by using "BinaryPeekStr()".

But there seems to be a limit as I was not able to extract a file of 25 kilobytes into a string variable. A file of 123 bytes could be processed without problems. Any ideas?

Answer:

Something like this (UNDEBUGGED!!!)
;===================================cut===============================


      infind="dog"
      outReplace="Poodle"

      infilename="c:\temp\xx.txt"
      outfilename="c:\temp\yy.txt"
      insize=FileSize(infilename)
      outsize=insize*2+100   ; Guess at how big output buffer needs to be


      inbuffer= BinaryAlloc(insize)
      outbuffer=BinaryAlloc(outsize)
      BinaryRead(inbuffer, infilename)

      ;BIG BIG BIG IMPORTANT ASSUMPTION
      ;THIS CODE ***ASSUMES*** "infind" will NOT occur at beginning of file

      outptr=0
      inptr=0
      while 1
          tempptr=BinaryIndex(inbuffer,inptr,infind,@fwdscan)
          if tempptr==0 then break    ; code simplification  See above
          BinaryCopy(outbuffer,outptr,inbuffer,inptr,insize-inptr)
          outptr=outptr+tempptr-inptr
          BinaryPokeStr(outbuffer,outptr,outReplace)
          outptr=outptr+strlen(outreplace)
          inptr=tempptr+strlen(infind)
	  if inptr >= insize then break
      endwhile
  
		BinaryWrite(outbuffer,outfilename)
      BinaryFree(inbuffer)
      BinaryFree(outbuffer)

;===================================cut===============================

The function BinaryReplace has now been added starting with version 99M of WinBatch.

str="dog"
rep="poodle"
infile="C:\Temp\xx.txt"

outfile="C:\Temp\yy.txt"
fs = FileSize( infile )
binbuf = binaryalloc( fs+100 )
ret = BinaryRead( binbuf, infile )
num = BinaryReplace( binbuf, str, rep ,0)
Message( "Number of '%str%' strings replaced", num )
BinaryWrite( binbuf, outfile )
exit

Article ID:   W12735
Filename:   Search and Replace in Binary Buffer.txt
File Created: 2000:03:27:13:57:22
Last Updated: 2000:03:27:13:57:22