18

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?

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
gadss
  • 21,687
  • 41
  • 104
  • 154

2 Answers2

33

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

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

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 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` – gadss May 23 '12 at 03:27
  • 2
    @gadss, it seems that you're closing the file before seeking when you should close it *after* seeking. – lhf May 23 '12 at 10:50
  • @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? – anthumchris Apr 30 '20 at 14:23
8

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)
MattJ
  • 7,924
  • 1
  • 28
  • 33
SatheeshJM
  • 3,575
  • 8
  • 37
  • 60