Lua io.read()

作者: AlbertS | 来源:发表于2016-07-23 21:54 被阅读7227次

前言#

前几章我们总结了文件的打开和关闭操作,而关于文件的操作怎么能少了对文件的读取,今天就来看看读取文件的具体操作,其实前几章中对于文件的读取都有所涉及,只是没有详细说明而已,接下来我们就看一下读取文件的具体参数。

内容#


io.read()##

  • 原型:io.read(...)
  • 解释:从文件中读取内容,还有另一种写法就是file:read(),而题目中的写法相当于对标准输入文件的操作,也就是io.input():read()。这个函数会根据所给的格式来读取内容内容,如果读不到所指定格式的内容则会返回nil,如果不指定读取的格式,则函数会选择*l做为默认的形式读取。
  • 其中可选的读取格式有:
  • "n"*:读取一个数字,这是唯一返回数字而不是字符串的读取格式。
  • "a"*:从当前位置读取余下的所有内容,如果在文件尾,则返回空串""
  • "l"*:读取下一个行内容,如果在文件尾部则会返回nil
  • number:读取number个字符的字符串,如果在文件尾则会返回nil,如果吧number=0,则这个函数不会读取任何内容而返回一个空串"",在文件尾返回nil

Usage##

  • 首先我们来新建一个文件,将文件命名为readtest.lua然后编写如下代码:
-- 打开文件
local file = io.open("readtest.txt", "r")
if nil == file then
    print("open file readtest.txt fail")
end

--  读取数字
local year = file:read("*n")
local month = file:read("*n")
local day = file:read("*n")
local hour = file:read("*n")

print("year = "..year)
print("month = "..month)
print("day = "..day)
print("hour = "..(hour or "nil"))

-- 读取行
local content = file:read("*l")
print("\ncontent = "..content)

-- 按行读取
local content2 = file:read("*l")
print("content2 = "..content2)

-- 读取0个字节
local zerobyte = file:read(0)
print("\nzerobyte = "..zerobyte)

-- 读取6个字节
local sixbyte = file:read(6)
print("sixbyte = "..sixbyte)

-- 读取所有内容
local readall = file:read("*a")
print("\nreadall = "..readall)

-- 文件结尾读取所有内容
local readallagain = file:read("*a")
print("readallagain = "..readallagain)

-- 文件结尾读取行
local reademptyline = file:read("*l")
if reademptyline == nil then
    print("\nread the end of file")
end

-- 文件尾读取0个字节
local zerobyteagain = file:read(0)
if zerobyteagain == nil then
    print("read the end of file")
end

file:close()
  • 运行结果
io_read.png

总结#

  • 使用函数要注意不同格式的读取返回nil""的情况,注意结尾的判断条件。
  • 图中所显示的就是程序的运行结果和读取的文件内容
  • 由结果可以看出这个实力程序几乎包括了所有读取文件的格式。
  • 从后几种情况可以判断出,几种不同的读取形式在文件结尾处的返回值是不同的,"*a"作用在结尾处返回空字符串"",而"*l""*n"number在结尾处返回nil

相关文章

网友评论

    本文标题:Lua io.read()

    本文链接:https://www.haomeiwen.com/subject/lhybjttx.html