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

Default files, os.remove and os.rename

io.write, io.read and friends use default files, and os handles deleting and renaming.

Default files, os.remove and os.rename

io.output(path) redirects io.write to a file and io.input(path) redirects io.read, while io.stdout and io.stderr are always available. os.rename(old, new) and os.remove(path) manage files and return true on success, or nil plus a message on failure. Passing no argument to io.output returns the current default output file.

Note: Restore the default output with io.output(io.stdout) before printing to the screen again.

Example: Default files, os.remove and os.rename

lua
local a, b = "/tmp/lua_demo_a.txt", "/tmp/lua_demo_b.txt"
io.output(a)
io.write("written through default output\n")
io.close()
io.output(io.stdout)

print(os.rename(a, b))
io.input(b)
print(io.read("l"))
io.close(io.input())
io.input(io.stdin)

print(os.remove(b))
print(select("#", os.remove(b)))

-- Output:
-- true
-- written through default output
-- true
-- 3
Common Mistakes
  1. Forgetting to restore io.output after redirecting
  2. Using os.remove on a file that does not exist and ignoring the failure
  3. Confusing io.write with file:write
Chapter Summary
  • io.output redirects io.write
  • io.input redirects io.read
  • os.rename and os.remove return true or nil plus a message
  • io.stdout and io.stderr are predefined
🔒

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.