Type Function
Object File
Library io.*
Return value Number
Revision Release 2024.3703
Keywords seek, files
See also io.open()


Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base.

The function can be used to get the current file position ("cur") or "set" the file position to the beginning, end, or any position between.

In case of success, the function returns the file position as a Number, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a String describing the error.


File:seek( [mode] [, offset] )
mode (optional)

String. Can be one of the following values:

  • "set" — base is position 0 (beginning of the file)
  • "cur" — base is current position (default)
  • "end" — base is end of file

The default value for mode is "cur", and for offset is 0. Therefore, the call File:seek() returns the current file position without changing it. The call File:seek("set") sets the position to the beginning of the file and returns 0. The call File:seek("end") sets the position to the end of the file, and returns its size.

offset (optional)

Number. Specifies the position for the "set" mode. The number is 0 based (which is the beginning of the file).


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