Appending and seeking
Append mode adds to the end, and seek moves the read or write position.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Opening with "w" instead of "a" and wiping the file
- Getting whence and offset in the wrong order
- 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: