lua获取文件倒数第n行的字符串

--获取已打开文件的倒数第n行字符串
local function getTail(file,num)
    if(io.type(file)~='file') then
        print('Error:'..tostring(file)..'is not a file,please check it')
        return nil
    end

    local readbyte,offset,linenum,preline=512,0,0,0
    while true do
        --每次读取readbyte个字符
        offset=offset-readbyte
        --每次读取偏移offset
        if file:seek("end",offset) == nil then
            -- 若没有num行则移到开始处并报错
            if offset + readbyte == 0 then
                file:seek("set")
            else
                print('Error:The file haven\'t '..num..' lines')
                return nil
            end
        end

        local data=file:read(readbyte)
         --翻转字符串方便找到倒数第num个换行符
        data = data:reverse()

        local index,start = 1,0
        while true do
            --查找换行符
            start = data:find("\n",index, true)
            if start == nil then
                break
            end
            --每找到一个换行符行数+1
            linenum = linenum + 1

            --当已找到第num个换行符
            if(linenum==num) then
                --输出第num行
                file:seek("end",offset+readbyte-start+1)

                return file:read(start-preline)
            end
            index=start+1
            preline=index
        end
    end
    return nil
end

猜你喜欢

转载自blog.csdn.net/sinat_30477313/article/details/81836221