Last active
February 11, 2021 17:24
-
-
Save diazvictor/1341da514e9f3d0d480cc99be74474bd to your computer and use it in GitHub Desktop.
How To Get the Size (In Bytes) Of A File Using Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This is a port of Bytes.go <https://gist.github.com/M1que4s/70965ab7ea03d85f43a379e0860d86eb> | |
function check(err, msg, ...) | |
local msg = string.format(msg, ...) | |
if err ~= nil then | |
print(msg) | |
return err | |
end | |
end | |
function read_byte(filename) | |
-- Holds the error | |
local err, t = nil, {} | |
-- Open the file, change the name for something in your system | |
local file, err = io.open(filename, 'rb') | |
check(err, 'Can\'t open file!') | |
-- Reads the data from the file and returns them in an array | |
repeat | |
local str, err = file:read(4*1024) | |
for b in (str or ''):gmatch'.' do | |
t[#t+1] = b:byte() | |
end | |
until not str | |
check(err, 'Can\'t read the file!') | |
-- Prints the size! | |
print(('File has %d bytes!\n'):format(#t)) | |
-- And close the file | |
err = file:close() | |
print('Can\'t close the file!') | |
end | |
-- Example of its use: | |
-- lua Bytes.lua <filename> | |
read_byte(arg[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment