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.

Replace First Instance of a String in a File


#DefineFunction ReplaceFirstString(str, replacestr, dafile)
	;***************************************
	;Replace first instance of a string in a file
	;***************************************
	;allocate and read in original file to buffer
	dafilesize = FileSize(dafile)
	buf1 = BinaryAlloc(dafilesize)
	BinaryRead (buf1, dafile)
	;allocate extra large secondary buffer
	buf2 = BinaryAlloc(dafilesize-StrLen(Str)+StrLen(replacestr))
	
	;find offset of the 'str' variable 
	offset = BinaryIndexEx( buf1, 0, str, @FWDSCAN, 0)
	;check if string not found
	if offset==-1 then return(0)
	
	if offset !=0
		;copy everything up to the offset of the 'str' variable
		bytescopied = BinaryCopy (buf2, 0, buf1, 0, offset)
	endif
	
	;insert replacement string in secondary buffer
	BinaryPokeStr(buf2, offset, replacestr)
	
	
	;copy the rest of the original buffer to the secondary buffer
	srcoffset = offset+StrLen(str)
	targetoffset = offset+StrLen(replacestr)
	remaining = BinaryEodGet(buf1)-srcoffset
	if remaining != 0 ;Check if end of buffer
	   BinaryCopy (buf2, targetoffset, buf1, srcoffset, remaining)
	endif
	
	;write out the updated file
	BinaryWrite (buf2, dafile)
	
	;clean up 
	BinaryFree(buf2)
	BinaryFree(buf1)
	
	return(1)
#EndFunction

;keep backup of original file and copy over
FileCopy ("c:\temp.old","c:\temp\temp.txt",@False)

dafile="c:\temp\temp.txt"

str = "READONLYMODEON=N"
replacestr = "READONLYMODEON=Y"
ReplaceFirstString(str, replacestr, dafile)


str = "READONLYMODEOFF=N"
replacestr = "READONLYMODEOFF=Y"
ReplaceFirstString(str, replacestr, dafile)

str = "KEYWORD=N"
replacestr = "KEYWORD=Y"
ReplaceFirstString(str, replacestr, dafile)

str = "HEADINGS=N"
replacestr = "HEADINGS=Y"
ReplaceFirstString(str, replacestr, dafile)
Exit

Article ID:   W15893
File Created: 2004:03:30:15:41:30
Last Updated: 2004:03:30:15:41:30