【问题标题】:Why is it still executing even if the file only has a 0 in it?为什么即使文件中只有一个 0 它仍然在执行?
【发布时间】:2022-01-13 05:30:17
【问题描述】:

这应该检查文件中是否有一个零,如果它不是零,它应该执行代码。 但是即使代码中只有一个零,它仍然会执行代码。

f = io.open("timesave.txt", "r")
if (f ~= 0) then
    io.input(f)
    resultstart = f:read("*line")
    resultstop = f:read("*line")
    f:close()
end

【问题讨论】:

  • 我不明白你想做什么 - 你想检查文件是否只包含一个字符 - 0 还是任何一行都包含 0?
  • 如果文件只包含数字0

标签: lua


【解决方案1】:

io.open("timesave.txt", "r") 如果成功或为零,则返回文件句柄。

发件人:https://www.lua.org/manual/5.4/manual.html#pdf-io.open

io.open(文件名[,模式])

此函数以字符串模式中指定的模式打开一个文件。 如果成功,它会返回一个新的文件句柄。 ...

您不能使用 io.open 来检查文件是否包含零。

为此,您需要打开文件,阅读并检查其内容。

-- open the file in read mode
local f = io.open("timesave.txt", "rb")
-- check wether the file has been opened
if not f then print("failed to open file") return end
-- read and check wether there is only a 0 in the file.
if f:read("a") == "\0" then print("file only contains \\0") end
f:close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2012-11-11
    • 2021-01-09
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2019-04-08
    相关资源
    最近更新 更多