Lua编程语言爱好者首页投稿(暂停使用,暂停投稿)

Lua io.read()

2016-07-23  本文已影响7227人  AlbertS

前言#

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

内容#


io.read()##


Usage##

-- 打开文件
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

总结#

上一篇下一篇

猜你喜欢

热点阅读