Lua如何读写二进制文件?

2026-04-01 20:031阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计613个文字,预计阅读时间需要3分钟。

Lua如何读写二进制文件?

我只想从二进制文件中读取/写入。我一直在关注this教程,它的工作原理……除了它似乎只是在写一个txt文件。我在测试时命名文件为test.bin,但日志可以打开并正确显示它,所以我认为它实际上并不。

我只是想从二进制文件中读/写.我一直在关注 this教程,它的工作原理……除了它似乎是在写一个txt文件.我在测试时命名文件test.bin,但记事本可以打开并正确显示它,所以我认为它实际上不是二进制文件.我已经说过它是一个带有“wb”和“rb”的二进制文件吗?

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字符写入文件,则可以在记事本或任何其他文本编辑器中打开它:

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

生成的文件将包含:

Lua如何读写二进制文件?

Hello

另一方面,如果您编写真正的二进制数据(例如随机字节),您将获得垃圾:

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()

这类似于您看过的那些视频游戏保存文件.

如果仍然没有得到它,请尝试将所有可能的八位字节写入文件:

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)打开它来查看对应关系:

这里,在左边,你有十六进制的字节,在右边你有他们的文字表示.我选择了大写字母H,正如您在左侧看到的那样,它对应于0x48. 0x48是基数10中的4 * 16 8 = 72(请查看屏幕截图的底部栏,告诉您).

现在看看我的第一个代码示例,猜猜小写e的代码是什么……

最后查看屏幕截图的最后4行(字节128到255).这是你看到的垃圾.

本文共计613个文字,预计阅读时间需要3分钟。

Lua如何读写二进制文件?

我只想从二进制文件中读取/写入。我一直在关注this教程,它的工作原理……除了它似乎只是在写一个txt文件。我在测试时命名文件为test.bin,但日志可以打开并正确显示它,所以我认为它实际上并不。

我只是想从二进制文件中读/写.我一直在关注 this教程,它的工作原理……除了它似乎是在写一个txt文件.我在测试时命名文件test.bin,但记事本可以打开并正确显示它,所以我认为它实际上不是二进制文件.我已经说过它是一个带有“wb”和“rb”的二进制文件吗?

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字符写入文件,则可以在记事本或任何其他文本编辑器中打开它:

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

生成的文件将包含:

Lua如何读写二进制文件?

Hello

另一方面,如果您编写真正的二进制数据(例如随机字节),您将获得垃圾:

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()

这类似于您看过的那些视频游戏保存文件.

如果仍然没有得到它,请尝试将所有可能的八位字节写入文件:

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)打开它来查看对应关系:

这里,在左边,你有十六进制的字节,在右边你有他们的文字表示.我选择了大写字母H,正如您在左侧看到的那样,它对应于0x48. 0x48是基数10中的4 * 16 8 = 72(请查看屏幕截图的底部栏,告诉您).

现在看看我的第一个代码示例,猜猜小写e的代码是什么……

最后查看屏幕截图的最后4行(字节128到255).这是你看到的垃圾.