如何将字符串附加到LUA中给定行的末尾?

时间:2015-03-13 22:09:19

标签: string lua append

我有一个带3个参数的工作函数。

function file.append(filename, linha, texto)
    filename = file.checkname(filename)
    if file.exists(filename) then  

    local hFile = io.open(filename, "r") --Reading.
    local lines = {}
    local restOfFile
    local lineCt = 1
    for line in hFile:lines() do
    if(lineCt == linha) then --Is this the line to modify?
        lines[#lines + 1] = line .. " " .. texto --Modify line by appending a string to the end.
        restOfFile = hFile:read("*a")
        break
    else
        lineCt = lineCt + 1
        lines[#lines + 1] = line
    end
    end
    hFile:close()

    hFile = io.open(filename, "w") --Write the file.
    for i, line in ipairs(lines) do
        hFile:write(line, "\n")
    end
    hFile:write(restOfFile)
    hFile:close()

    end -- end file.exists()
end

这个函数的问题在于它读取整个.txt文件,然后逐行重写,将“text”附加到指定的“line”,其他所有内容都不会改变。

因为它会读取然后重写整个.txt文件,所以它可能无法写入文件,而是将其留空。这很少发生,但是当它发生时,我会失去一切。

我需要一个函数来简单地附加到给定行的末尾而不重写整个文件。任何人都可以帮助我吗?

0 个答案:

没有答案
相关问题