读/写二进制文件 [英] Reading/Writing Binary files

查看:78
本文介绍了读/写二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从二进制文件读取/写入.我一直在关注教程,该教程可以正常工作……只是它似乎在写一些东西. txt文件.我在测试文件时将其命名为test.bin,但记事本可以将其打开并正确显示,因此我认为它实际上不是二进制文件.我告诉过它这是一个带有"wb"和"rb"的二进制文件吗?

I'm just trying to read/write from a binary file. I've been following this tutorial, and it works... except 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 properly, so I don't think it's actually a binary file. I've told it that it's a binary file 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

推荐答案

如果仅将ASCII字符写入文件,则可以在记事本或任何其他文本编辑器中将其打开就可以了:

If you only write ASCII characters to a file, it will be possible to open it in Notepad or any other text editor just fine:

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

结果文件将包含:

Hello

另一方面,如果您写入真实的二进制数据(例如随机字节),则会得到垃圾:

On the other hand if you write real binary data (for instance 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 those video game save files you have seen.

如果仍然无法获取,请尝试将所有可能的八位字节写入文件:

If you still don't get it, try to write 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()

,然后使用十六进制编辑器(在Mac OS上使用Hex Fiend)打开它,以查看对应关系:

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

在这里,您的左侧是十六进制的字节,而右侧则是其文本表示形式.我选择了大写字母 H ,如左图所示,它对应于0x48.以10为底的0x48是4 * 16 + 8 = 72(请看截图的底部,告诉您).

Here, on the left, you have the bytes in hexadecimal and on the right you have their text representation. I have selected uppercase H which, as you can see on the left, corresponds to 0x48. 0x48 is 4*16 + 8 = 72 in base 10 (look at the bottom bar of the screenshot which tells you that).

现在来看我的第一个代码示例,并猜测小写字母 e 的代码是什么...

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

最后查看屏幕快照的最后4行(字节128至255).这是您看到的垃圾.

And finally look at the 4 last rows of the screenshot (bytes 128 to 255). This is the garbage you were seeing.

这篇关于读/写二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆