类型 函数 对象 文件 库 io.* 返回值 数字 修订版 2024.3703 版 关键字 seek,文件 另请参阅 io.open()
设置并获取文件位置,依据是文件开头开始测量,位置由 offset 加上基础值指定。
可利用该函数获取当前文件位置("cur"
)或"set"
,将文件位置设置为开头、结尾或两者之间的任何位置。
如果成功,该函数将返回一个 数字,表示文件开头开始测量的文件位置(以字节为单位)。如果该函数失败,它将返回 nil
加上一个 字符串 来描述该错误。
File:seek( [mode] [, offset] )
字符串. 可以是下列值之一
"set"
— 基础值为位置 0(文件开头)"cur"
— 基础值为当前位置(默认)"end"
— 基础值为文件结尾mode 的默认值是 "cur"
,offset 的默认值是 0
。因此,调用 File:seek()
会返回当前文件位置而不改变它。调用 File:seek("set")
会将位置设置为文件开头并返回 0
。调用 File:seek("end")
会将位置设置为文件结尾并返回文件大小。
数字. 为 "set"
模式指定位置。该数字以 0
为基础(它是文件开头)。
local fh = io.tmpfile() fh:write( "My temporary file data" ) fh:flush() -- Ensure data written to file print( "file position: ", fh:seek() ) -- Show current position fh:seek( "set", 0 ) -- Reset file position to beginning local content = fh:read( "*a" ) -- Read all the file print( "File content: " .. content ) print( "file position: ", fh:seek("end") ) -- Show the end position of file