Get File Size in Cocos2d-x Lua with io.open, seek and Error Handling

This helper returns the size of a file in bytes. It returns false when the file cannot be opened.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function io.filesize(path)
    local file = io.open(path, "rb")
    if not file then
        return false
    end

    local current = file:seek()
    local size = file:seek("end")
    file:seek("set", current)
    file:close()
    return size
end

Binary mode avoids platform-specific text newline translation. The function saves and restores the original cursor position, although that is mainly useful if adapted to accept an already-open handle.