Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何将字符串附加到LUA中给定行的末尾?_String_Lua_Append - Fatal编程技术网

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

String 如何将字符串附加到LUA中给定行的末尾?,string,lua,append,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 =

我有一个具有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文件,然后逐行重写,在指定的“行”后面附加“文本”,其他所有内容都保持不变

由于它读取然后重写整个.txt文件,因此可能无法写入该文件,使其为空。这种情况很少发生,但一旦发生,我就失去了一切


我需要一个函数来简单地附加到给定行的末尾,而不重写整个文件。有人能帮我吗?

第一个安全步骤:使用一个临时文件作为输出,只有在行数合理且写操作有效的情况下才在顶部重命名。您还可以在一个循环中读写,而不是将行收集到表中(并且具有更好的内存行为)。@Etan Reisner写入辅助文件,然后检查行数是否匹配,这是一个好主意。我想在不重写整个文件的情况下,不可能附加到指定行的末尾。或者是吗?一旦找到行,您的读取循环也会终止,这是故意的吗?在找到的行截断文件。修改后需要重写所有内容。从技术上讲,如果您正在进行操作(您没有),那么在此之前不需要重写任何内容。我的意思不是计算输出文件的行数,我的意思是根据您读取的行数检查表的大小。尽管检查实际写入的文件也是一个合理的想法(如果成本更高的话)。