Getting file properties

Files / Basic operations

local lfs = require("lfs")

local file_name = "file.txt"
local out = assert(io.open(file_name, "w"))
out:write("Line 1\nLine 2\n")
out:close()

-- Pin the modification time: 2027-01-01 22:13:20
local moment = 1798841600
lfs.touch(file_name, moment, moment)

-- The size: seek to the end gives it
local file = assert(io.open(file_name, "rb"))
local size = file:seek("end")
file:close()
-- size = 14

-- lfs.attributes gives a table of properties
local info = lfs.attributes(file_name)
-- info.mode = file
-- info.size = 14
local modified = os.date("!%Y-%m-%d %H:%M:%S",
                         info.modification)
-- modified = 2027-01-01 22:13:20

-- One property by name
local dir_mode = lfs.attributes(".", "mode")
-- dir_mode = directory

-- A missing file gives nil (and a message)
local missing = lfs.attributes("missing.txt")
-- missing = nil

print("size = " .. size)
print("info.mode = " .. info.mode)
print("info.size = " .. info.size)
print("modified = " .. modified)
print("dir_mode = " .. dir_mode)
print("missing = " .. tostring(missing))