deleting all files in documents directory

4 replies [Last post]
ansaf_130
User offline. Last seen 21 weeks 2 days ago. Offline
Joined: 26 Aug 2012

I want to add a functionality in my app that if user press back button without saving his/her data, all saved files in documents directory get deleted.. Now I dont know how to completely flush this directory. Can anybody help me here?

Replies

ingemar
User offline. Last seen 28 min 1 sec ago. Offline
Joined: 20 Jun 2011

Have a look at these links
http://docs.coronalabs.com/api/library/lfs/index.html
http://docs.coronalabs.com/api/library/os/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
local lfs = require "lfs";
 
local doc_dir = system.DocumentsDirectory;
local doc_path = system.pathForFile("", doc_dir);
local resultOK, errorMsg;
 
for file in lfs.dir(doc_path) do
   local theFile = system.pathForFile(file, doc_dir);
        
   if (lfs.attributes(theFile, "mode") ~= "directory") then
      resultOK, errorMsg = os.remove(theFile);
 
      if (resultOK) then
         print(file.." removed");
      else
         print("Error removing file: "..file..":"..errorMsg);
      end
   end
end

ansaf_130
User offline. Last seen 21 weeks 2 days ago. Offline
Joined: 26 Aug 2012

it is working ...
Although its not an issue but just for the curiosity that this loop not only delete the files in documents directory but also delete the complete folder `/documents` ...
Is it possible that the directory become empty but not deleted
On relaunching the project, it is there,so not an issue
Thank you

ingemar
User offline. Last seen 28 min 1 sec ago. Offline
Joined: 20 Jun 2011

Ooops! That's what I get for writing code in a post without testing... really sorry for that.
I forgot that it returned the system files "." and ".." Ouch!

Anyway the code above has been modified to test for directories now and should only remove all files...

ansaf_130
User offline. Last seen 21 weeks 2 days ago. Offline
Joined: 26 Aug 2012

well this too deleting \documents directory.
I dont know why as check is there but still..!!

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.