Lua:防止二进制代码中的回车

发布于 2024-12-28 13:24:48 字数 361 浏览 1 评论 0原文

我正在尝试从二进制文件中读取一个块。这工作正常,但是,每当代码中存在 0x0A 时,Lua 就会插入 0x0D 并将其转换为换行符,这会导致文件出现乱码。我怎样才能防止这种情况发生?我检查了几个用于编写二进制文件的源代码,它们使用与我相同的 io.write() 函数。我对 Lua 还很陌生,所以可能我错过了一些东西。这是我的代码:

file=io.open(filepath,'rb')
file:seek("set")
file:seek("cur",startoffset)
filecontent=file:read(endoffset-startoffset)
io.output(test.tmp)
io.write(filecontent)

I'm trying to read a chunk from a binary file. This works fine, however, whenever there's a 0x0A in the code, Lua inserts a 0x0D and turns it into a line break, which garbles the file. How can I prevent that? I checked out several source codes for writing binary files and they use the same io.write()-function I do. I'm still new to Lua, so may be I missed something. Here's my code:

file=io.open(filepath,'rb')
file:seek("set")
file:seek("cur",startoffset)
filecontent=file:read(endoffset-startoffset)
io.output(test.tmp)
io.write(filecontent)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两个我 2025-01-04 13:24:48

我检查了几个用于编写二进制文件的源代码,它们使用与我相同的 io.write() 函数。

不,他们没有。他们使用file:write。有区别。其中之一作用于给定的文件句柄。另一个适用于“默认输出文件”,该文件始终以文本形式打开。

您想要的正确 Lua 代码是这样的:

local file = assert(io.open(filepath, "rb"), "Could not open file for reading.")
local filecontent = file:read("*a")
file:close()
file = assert(io.open("temp.tmp", "wb"),  "Could not open file for writing.")
file:write(filecontent)
file:close()

I checked out several source codes for writing binary files and they use the same io.write()-function I do.

No, they don't. They use file:write. There's a difference. One works on a given file handle. The other works on the "default output file", which is always opened as text.

The correct Lua code for what you want is this:

local file = assert(io.open(filepath, "rb"), "Could not open file for reading.")
local filecontent = file:read("*a")
file:close()
file = assert(io.open("temp.tmp", "wb"),  "Could not open file for writing.")
file:write(filecontent)
file:close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文