Read / write binary files

I am just trying to read / write from a binary file. I am following this tutorial and it works ... except that it seems to be writing things to a txt file. I named the file test.bin when testing it, but notepad can open it and display it correctly, so I do not consider it a binary file. I said this is a binary with "wb" and "rb" right?

if arg[1] == "write" then local output = assert(io.open(arg[2], "wb")) output:write(arg[3]) --3rd argument is written to the file. assert(output:close()) elseif arg[1] == "read" then local input = assert(io.open(arg[2], "rb")) print(input:read(1)) --Should read one byte, not one char/int. Right? end 
+6
source share
2 answers

If you write only ASCII characters to a file, you can simply open it in Notepad or any other text editor:

 local out = io.open("file.bin", "wb") local str = string.char(72,101,108,108,111,10) -- "Hello\n" out:write(str) out:close() 

The resulting file will contain:

 Hello 

On the other hand, if you write real binary data (e.g. random bytes), you will get garbage:

 local out = io.open("file.bin", "wb") local t = {} for i=1,1000 do t[i] = math.random(0,255) end local str = string.char(unpack(t)) out:write(str) out:close() 

This is similar to the saved video game files you saw.

If you still don’t get it, try writing all possible octets to a file:

 local out = io.open("file.bin", "wb") local t = {} for i=0,255 do t[i+1] = i end local str = string.char(unpack(t)) out:write(str) out:close() 

and then open it with a hex editor (here I used Hex Fiend on Mac OS) to see the corresponding matches:

hex

Here, on the left, you have bytes in hexadecimal order, and on the right is a textual representation. I chose the capital letter H, which, as you see on the left, corresponds to 0x48. 0x48 is 4 * 16 + 8 = 72 in base 10 (look at the bottom panel of the screenshot, which tells you about it).

Now look at my first code example and guess what the code is for lowercase e ...

And finally, look at the last 4 lines of the screenshot (bytes 128 through 255). This is the trash that you saw.

+11
source

I do not understand how to write binaries

My levels created on an old computer and my new game can read 2200 bytes each level 129

I still do not understand how I can use the table xdata (data level) can write to a file.

  function xdatatoline (levelnumber,xdata) local out = io.open("file.bin", "wb") local t = xdata --for i=1,1000 do t[i] = math.random(0,255) end local str = string.char(unpack(t)) out:write(str) out:close() end 

BAD ARGUMENT # 1 to CHAR expected number, received string)

0
source

Source: https://habr.com/ru/post/948672/


All Articles