当前位置 博文首页 > lua文件操作详解

    lua文件操作详解

    作者:admin 时间:2021-01-31 21:12

    I/O库提供两种不同的方式进行文件处理:

    io表调用方式

    使用io表,io.open将返回指定文件的描述,并且所有的操作将围绕这个文件描述。io表同样提供三种预定义的文件描述io.stdin,io.stdout,io.stderr

    文件句柄直接调用方式
    即使用file:XXX()函数方式进行操作,其中file为io.open()返回的文件句柄。多数I/O函数调用失败时返回nil加错误信息,有些函数成功时返回nil

    IO
    io.close ([file])
    io.flush ()
    相当于file:flush(),输出所有缓冲中的内容到默认输出文件

    io.lines ([filename])
    打开指定的文件filename为读模式并返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,并自动关闭文件,若不带参数时io.lines() <=> io.input():lines(); 读取默认输入设备的内容,但结束时不关闭文件

    for line in io.lines("main.lua") do
      print(line)
    end
    

    io.open (filename [, mode])
    mode:

      "r": 读模式 (默认);

      "w": 写模式;

      "a": 添加模式;

      "r+": 更新模式,所有之前的数据将被保存

      "w+": 更新模式,所有之前的数据将被清除

      "a+": 添加更新模式,所有之前的数据将被保存,只允许在文件尾进行添加

      "b": 某些系统支持二进制方式

    io.read (...)
    io.type (obj)
    检测obj是否一个可用的文件句柄

    返回:

      "file":为一个打开的文件句柄

      "closed file":为一个已关闭的文件句柄

      nil:表示obj不是一个文件句柄

    io.write (...)
    相当于io.output():write

    File

    file:close()
    当文件句柄被垃圾收集后,文件将自动关闭。句柄将变为一个不可预知的值

    file:flush()
    向文件写入缓冲中的所有数据

    file:lines()
    返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,但不关闭文件

    for line in file:lines() do body end

    file:read(...)

    按指定的格式读取一个文件,按每个格式函数将返回一个字串或数字,如果不能正确读取将返回nil,若没有指定格式将指默认按行方式进行读取

    格式:

      "n": 读取一个数字 ("number")

      "a": 从当前位置读取整个文件,若为文件尾,则返回空字串 ("all")

      "l": [默认]读取下一行的内容,若为文件尾,则返回nil ("line")

      number: 读取指定字节数的字符,若为文件尾,则返回nil;如果number为0则返回空字串,若为文件尾,则返回nil;

    file:seek(whence)

    设置和获取当前文件位置,成功则返回最终的文件位置(按字节),失败则返回nil加错误信息

    参数

    whence:

      "set": 从文件头开始

      "cur": 从当前位置开始[默认]

      "end": 从文件尾开始

    offset:默认为0

      不带参数file:seek()则返回当前位置,file:seek("set")则定位到文件头,file:seek("end")则定位到文件尾并返回文件大小

    file:write(...)

    按指定的参数格式输出文件内容,参数必须为字符或数字,若要输出其它值,则需通过tostring或string.format进行转换

    实例
    读取文件所有内容

    function readfile(path)
      local file = io.open(path, "r")
      if file then
        local content = file:read("*a")
        io.close(file)
        return content
      end
      return nil
    end
    

    写入内容到文件

    function writefile(path, content, mode)
      mode = mode or "w+b"
      local file = io.open(path, mode)
      if file then
        if file:write(content) == nil then return false end
        io.close(file)
        return true
      else
        return false
      end
    end
    

    文件大小

    -- @return : 文件字节数
    function filesize(path)
      local size = false
      local file = io.open(path, "r")
      if file then
        local current = file:seek()
        size = file:seek("end")
        file:seek("set", current)
        io.close(file)
      end
      return size
    end
    

    文件是否存在

    function fileExists(path)
      local file = io.open(path, "r")
      if file then
        io.close(file)
        return true
      end
      return false
    end

    js
    下一篇:没有了