依赖模块
md5模块
下载地址:
https://github.com/kikito/md5.lua/blob/master/md5.lua
这个模块是纯粹lua实现的md5算法,运算md5的速度有点慢。
luafilesystem模块
下载地址:
https://github.com/lunarmodules/luafilesystem
这个模块实现了在lua中访问linux文件系统的功能,可以通过此模块递归遍历每一个子文件夹下的文件。
源码实现
md5 = require "md5"
lfs = require "lfs"
md5file = {}
md5file.__index = md5file
function md5file:new(path)
local object = {path = path, md5obj = md5:new()}
setmetatable(object, self)
return object
end
function md5file:get_md5sum()
local file=assert(io.open(self.path, "rb"))
local len = assert(file:seek("end"))
assert(file:seek("set"))
local read_len = 8192
for i=0,len,read_len do
local readbuf=file:read(read_len)
if readbuf == '' or readbuf == nil then
break
end
self.md5obj:update(readbuf)
end
file:close()
return self.md5obj:finish()
end
function md5dir(path)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path.. '/' ..file
local attr = lfs.attributes (f)
if attr.mode == "directory" then
md5dir(f)
else
print(f, md5.tohex(md5file:new(f):get_md5sum()))
end
end
end
end
md5dir(".") --test files in current folder
运行如图
经验证,与系统命令行运算的结果一致。
源码下载:
[https://download.csdn.net/download/wjg220000/87690034]