Archive: Writing binary to file


Writing binary to file
Hey guys.
My installer needs to write some code to a config file, which happens to be binary.

Every time I use 'FileOpen' / 'FileWrite' - the result is that the string is truncated after the first binary character (ie, non ascii)

Is there a binary-safe way to write to a file?

This is sending me nuts!
Thanks


Use FileWriteByte.


Hi, thanks for the swift reply.
The documentation for this (http://nsis.sourceforge.net/Docs/Chapter4.html) is somewhat sparse.

Do I have to write it byte by byte, or can I pass a collection of values.

For example, to write 6162636465 (abcdef in ascii)

Can I do:
FileWriteByte "6162636465"

Or do I have to do:

FileWriteByte "61"
FileWriteByte "62"
.. and so on


If it's the later, would you be able to give me a leg up on how I would loop/iterate over the 'string'?

IE, In PHP, I'd be doing:
foreach(chunk_split('6162636465',2) as $v) FileWriteByte $v

Thanks kindly - I appreciate your help.


Byte by byte.


Thanks.

For anyone interested, this is my code:
Possibly buggy, particulally in the return parts, but it seems to work...

outFile "installer.exe"
!define writeHex "!insertmacro writeHex"

!macro writeHex File String
Push "${String}"
Push "${File}"
Call writeHex
!macroend

Function writeHex
ClearErrors
Exch $0 ; Stack: $0 <string>
Exch ; Stack: <string> $0
Exch $1 ; Stack: $1 $0
Push $2 ; Stack: $2 $1 $0
Push $3
Push $4

Push 0
Pop $4
FileOpen $2 "$0" "w"

Loop:
StrCpy $3 $1 2 $4 ; Get next characters
StrCmp $3 "" Done
IntFmt $3 "%d" "0x$3"
FileWriteByte $2 $3
IntOp $4 $4 + 2
Goto Loop

Done:
FileClose $2
Pop $2 ; Stack: $1 $0
Pop $1 ; Stack: $0
Pop $0 ; Stack: -empty-

FunctionEnd

Section Test
${writeHex} "c:\temp\test\a_log_file.txt" "65666768"
SectionEnd