【问题标题】:Why doesn't io:write() write to the output file?为什么 io:write() 不写入输出文件?
【发布时间】:2013-03-06 20:39:36
【问题描述】:

我正在用 Lua 编写一个简短的脚本来复制搜索/替换功能。目标是输入搜索词和替换词,它将梳理给定扩展名的所有文件(尚未输入确定)并将搜索词替换为替换词。

一切似乎都在做它应该做的事情,除了文件实际上并没有被写入。我的 Lua 解释器(自己在 Pelles-C 中编译)不会抛出任何错误或异常退出;脚本完成就像它工作一样。

起初我没有 i:flush(),但我在读到它应该将任何写入的数据保存到文件后添加它(参见 LUA docs)。它没有改变任何东西,文件仍然没有被写入。

认为这可能与我打开文件进行编辑的方式有关,因为“w”选项有效(但会覆盖我的测试文件中的所有内容)。

来源:

io.write("Enter your search term:")
term = io.read()

io.write("Enter your replace term:")
replacement = io.read()

io.stdin:read()

t = {}
for z in io.popen('dir /b /a-d'):lines() do

    if string.match(string.lower(z), "%.txt$")  then
        print(z)
        table.insert(t, z)
    end
end
print("Second loop")

for _, w in pairs(t) do
    print(w)
    i = io.open(w, "r+")
    print(i)

    --i:seek("set", 6)
    --i:write("cheese")
    --i:flush()
    for y in i:lines() do
        print(y)
        p, count = string.gsub(y, term, replacement, 1)
        print(p)

        i:write(p)

        i:flush()
        io.stdin:read()
    end
    i:close()
end

这是我得到的输出(这是我想要发生的),但实际上并没有被写入文件:

有一次它把输出写到一个文件,但它只输出到一个文件,然后写我的脚本就崩溃了,消息是:No error。行号在for y in i:lines() do 行,但我不知道它为什么会在那里中断。我注意到file:lines() 会中断,如果文件本身没有任何内容并给出奇怪/乱码错误,但我的文本文件中有内容。

编辑1

我尝试在我的 for 循环中这样做:

for y in i:lines() do
        print(y)
        p, count = string.gsub(y, term, replacement, 1)
        print(p)

        i:write(p)
        i:seek("set", 3)        --New
        i:write("TESTESTTEST")  --New
        i:flush()
        io.stdin:read()
end

为了看看我是否可以强制它写常规文本。 确实,但随后它因No error 而崩溃,并且仍然不写入替换字符串(只是 TESTESTTEST)。不知道是什么问题。

【问题讨论】:

    标签: file-io lua


    【解决方案1】:

    我猜,在遍历文件行时不能写入文件

    for y in i:lines() do
       i:write(p)
       i:flush()
    end
    

    【讨论】:

    • 我认为你是对的。将 i:write(p) 行移出循环似乎让它写入文件。除非发生任何其他事情,否则我会将其标记为正确。谢谢。
    猜你喜欢
    • 2011-11-05
    • 2013-01-11
    • 2018-10-11
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多