← Back to Lua Course | Chapter 8: File I/O | Lesson 5 of 7

Appending and seeking

Append mode adds to the end, and seek moves the read or write position.

In this page:

  1. Appending and seeking

Appending and seeking

Opening a file with "a" adds new text at the end and keeps the old content. file:seek(whence, offset) moves the position, where whence is "set" for the start, "cur" for the current position and "end" for the end, and it returns the new position. seek("end") is a quick way to find the file size.

Note: file:seek() with no arguments returns the current position without moving.

Example: Appending and seeking

lua
local path = "/tmp/lua_demo_append.txt"
local f = assert(io.open(path, "w"))
f:write("abc\n")
f:close()

f = assert(io.open(path, "a"))
f:write("def\n")
f:close()

f = assert(io.open(path, "r"))
print(f:seek("end"))
f:seek("set", 4)
print(f:read("l"))
print(f:seek())
f:close()

-- Output:
-- 8
-- def
-- 8
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Opening with "w" instead of "a" and wiping the file
  2. Getting whence and offset in the wrong order
  3. Forgetting that seek counts bytes from zero
Chapter Summary
  • "a" appends at the end
  • seek("set", n) jumps from the start
  • seek("end") returns the size
  • seek() returns the current position
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.