How to get the file size and delete file in Lua?

31,184

Solution 1

The size is given by myFile:seek("end").

To delete the file, use os.remove(path). But close the file first.

Solution 2

Recently Lua File System support was added to Corona! You can get file size using

local lfs = require "lfs"
local size = lfs.attributes (path, "size")

You can have a read here http://keplerproject.github.com/luafilesystem/manual.html#reference

To delete the file use

os.remove(path)
Share:
31,184
gadss
Author by

gadss

Looking for the best motorcycle helmet reviews? I will guide you to choose the style that you want according to your needs. So let’s gear up! Also, it include reviews about the best motorcycle jackets, gloves, pants, boots, tire and other parts. It is for both men and women choice

Updated on July 21, 2022

Comments

  • gadss
    gadss almost 2 years

    I have problem in getting the size of the file using Lua. I am creating a function method that if the file size of the file is 743 bytes, then the file will be deleted.

    Here is my code :

    local getDLFile = function(fileToDL)
                local path = system.pathForFile(fileToDL, system.DocumentsDirectory )
                local myFile = io.open( path, "w+b" ) 
                http.request{ 
                    url = "http://www.testfile.com/"..fileToDL, 
                    sink = ltn12.sink.file(myFile),
                }
    
                -- i don't know what is the syntax
                if myFile.size == 743 bytes then
                     myFile.delete
                end             
    
    end
    

    Can anyone can help me about my case?

  • gadss
    gadss almost 12 years
    thanks lhf for your answer, i try to print(myFile:seek("end")) but i god these error in my corona Runtime error ...ne\my documents\singing idol final game\freeplay.lua:258: attempt to use a closed file stack traceback: [C]: ? [C]: in function 'seek' ...ne\my documents\singing idol final game\freeplay.lua:258: in function 'getDLFile' ...ne\my d
  • lhf
    lhf almost 12 years
    @gadss, it seems that you're closing the file before seeking when you should close it after seeking.
  • AnthumChris
    AnthumChris about 4 years
    @lhf Is it necessary to seek file to previous position before seek("end") or does that have no impact for one-off file size getting?