如何在Lua中获取最后修改时间戳

我正在尝试处理 Lua 文件。因此,我能够打开、读取、写入、关闭文件。

local session_debug = io.open("/root/session_debug.txt", "a")
session_debug:write("Some text\n")
session_debug:close()

如何知道该文件的上次修改日期时间戳?

点赞
用户1009479
用户1009479

没有内置的 Lua 函数可以实现这个功能。一个不使用第三方库的方法是利用io.popen

例如,在 Linux 上,你可以使用stat

local f = io.popen("stat -c %Y testfile")
local last_modified = f:read()

现在last_modifiedtestfile的最后修改时间戳。在我的系统上,

print(os.date("%c", last_modified))

输出 Sat Mar 22 08:36:50 2014

2015-10-23 08:10:33
用户1007991
用户1007991

如果您不介意使用库,LuaFileSystem 可以让您通过以下方式获取修改时间戳:

local t = lfs.attributes(path, 'modification')

以下是带有错误处理的更详细的示例(将打印传递给脚本的第一个参数的名称和修改日期):

local lfs = require('lfs')
local time, err = lfs.attributes(arg[1], 'modification')
if err then
    print(err)
else
    print(arg[1], os.date("%c", time))
end
2020-02-22 13:53:45