How to replace data in a binary file?

Just starting out? Need help? Post your questions and find answers here.
AZJIO
Addict
Addict
Posts: 1318
Joined: Sun May 14, 2017 1:48 am

How to replace data in a binary file?

Post by AZJIO »

How to replace data in a binary file?
I found a discussion topic, but it's old and I'm not sure if the code is correct.
I am considering that it is necessary to search for the first byte in memory and if found, then check the 2nd byte, etc. And it would also be possible to get a character in another register (NoCase) and check 2 characters at once at the same position.
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: How to replace data in a binary file?

Post by Mijikai »

You can check as many bytes as you need before moving on in the search.
I remembered this thread about strings: viewtopic.php?t=71807
AZJIO
Addict
Addict
Posts: 1318
Joined: Sun May 14, 2017 1:48 am

Re: How to replace data in a binary file?

Post by AZJIO »

Tried this one, it worked.

Code: Select all

EnableExplicit

Define Path$, length, *mem, bytes, pos, posEnd, Size, *Buffer

#File = 0
; Path$ = OpenFileRequester("", "", "Text (.txt)|*.txt|All (*.*)|*.*", 0)
Path$ = "C:\grldr"
If Path$
	If ReadFile(#File, Path$)
		length = Lof(#File)
		*mem = AllocateMemory(length)
		If *mem
			bytes = ReadData(#File, *mem, length)
			Debug "bytes: " + Str(bytes)
		EndIf
		CloseFile(#File)
	EndIf
EndIf

NewList BinList.s()

If bytes
	pos = *mem
	posEnd = *mem + bytes
	While pos < posEnd
		If AddElement(BinList())
			BinList() = PeekS(pos, -1, #PB_Ascii)
			pos + StringByteLength(BinList(), #PB_Ascii) + 1
		EndIf
	Wend
	
	Debug ListSize(BinList())
	ForEach BinList()
		If Asc(BinList())
			If FindString(BinList(), "menu")
				ReplaceString(BinList(), "menu", "mina", #PB_String_InPlace)
				; 			Debug BinList()
			EndIf
		EndIf
	Next
	Size = 0
	pos = *mem
	ForEach BinList()
		If Asc(BinList())
			Size = StringByteLength(BinList(), #PB_Ascii) + 1
			*Buffer = Ascii(BinList())
			CopyMemory(*Buffer, pos, Size)
			FreeMemory(*Buffer)
			pos + Size
		Else
			CopyMemory(@"", pos, 1)
			pos + 1
		EndIf
		If pos >= posEnd
			Break
		EndIf
	Next
	
	If CreateFile(#File, "C:\Temp\grldr")
		WriteData(#File, *mem, bytes)
		CloseFile(#File)
	EndIf
EndIf
If *mem
	FreeMemory(*mem)
EndIf
Post Reply